task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Wart | Wart | (rev "asdf") |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #REXX | REXX | /*REXX program to demonstrate FIFO queue usage by some simple operations*/
call viewQueue
a="Fred"
push /*puts a "null" on top of queue.*/
push a 2 /*puts "Fred 2" on top of queue.*/
call viewQueue
queue "Toft 2" /*put "Toft 2" on queue bottom.*/
queue /*put a "null" on queue bottom.*/
call viewQueue
do n=1 while queued()\==0
parse pull xxx
say "queue entry" n': ' xxx
end /*n*/
call viewQueue
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────viewQueue subroutine────────────────*/
viewQueue: if queued()==0 then say 'Queue is empty'
else say 'There are' queued() 'elements in the queue'
return |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #LDPL | LDPL | DATA:
A IS NUMBER VECTOR
C IS TEXT
N IS NUMBER
I IS NUMBER
J IS NUMBER
PROCEDURE:
SUB-PROCEDURE SHOWU
STORE 0 IN I
WHILE I IS LESS THAN N DO
DISPLAY " STORE "
DISPLAY A:I
DISPLAY " IN "
DISPLAY " A:"
DISPLAY I CRLF
ADD I AND 1 IN I
REPEAT
DISPLAY " STORE "
DISPLAY N
DISPLAY " IN N" CRLF
END SUB-PROCEDURE
SUB-PROCEDURE SHOW
STORE 0 IN J
WHILE J IS LESS THAN N DO
IF A:J IS EQUAL TO 42 THEN
CALL SUB-PROCEDURE SHOWU
ELSE
STORE CHARACTER A:J IN C
DISPLAY C
END-IF
ADD J AND 1 IN J
REPEAT
END SUB-PROCEDURE
STORE 10 IN A:0
STORE 68 IN A:1
STORE 65 IN A:2
STORE 84 IN A:3
STORE 65 IN A:4
STORE 58 IN A:5
STORE 10 IN A:6
STORE 32 IN A:7
STORE 32 IN A:8
STORE 65 IN A:9
STORE 32 IN A:10
STORE 73 IN A:11
STORE 83 IN A:12
STORE 32 IN A:13
STORE 78 IN A:14
STORE 85 IN A:15
STORE 77 IN A:16
STORE 66 IN A:17
STORE 69 IN A:18
STORE 82 IN A:19
STORE 32 IN A:20
STORE 86 IN A:21
STORE 69 IN A:22
STORE 67 IN A:23
STORE 84 IN A:24
STORE 79 IN A:25
STORE 82 IN A:26
STORE 10 IN A:27
STORE 32 IN A:28
STORE 32 IN A:29
STORE 67 IN A:30
STORE 32 IN A:31
STORE 73 IN A:32
STORE 83 IN A:33
STORE 32 IN A:34
STORE 84 IN A:35
STORE 69 IN A:36
STORE 88 IN A:37
STORE 84 IN A:38
STORE 10 IN A:39
STORE 32 IN A:40
STORE 32 IN A:41
STORE 78 IN A:42
STORE 32 IN A:43
STORE 73 IN A:44
STORE 83 IN A:45
STORE 32 IN A:46
STORE 78 IN A:47
STORE 85 IN A:48
STORE 77 IN A:49
STORE 66 IN A:50
STORE 69 IN A:51
STORE 82 IN A:52
STORE 10 IN A:53
STORE 32 IN A:54
STORE 32 IN A:55
STORE 73 IN A:56
STORE 32 IN A:57
STORE 73 IN A:58
STORE 83 IN A:59
STORE 32 IN A:60
STORE 78 IN A:61
STORE 85 IN A:62
STORE 77 IN A:63
STORE 66 IN A:64
STORE 69 IN A:65
STORE 82 IN A:66
STORE 10 IN A:67
STORE 32 IN A:68
STORE 32 IN A:69
STORE 74 IN A:70
STORE 32 IN A:71
STORE 73 IN A:72
STORE 83 IN A:73
STORE 32 IN A:74
STORE 78 IN A:75
STORE 85 IN A:76
STORE 77 IN A:77
STORE 66 IN A:78
STORE 69 IN A:79
STORE 82 IN A:80
STORE 10 IN A:81
STORE 80 IN A:82
STORE 82 IN A:83
STORE 79 IN A:84
STORE 67 IN A:85
STORE 69 IN A:86
STORE 68 IN A:87
STORE 85 IN A:88
STORE 82 IN A:89
STORE 69 IN A:90
STORE 58 IN A:91
STORE 10 IN A:92
STORE 10 IN A:93
STORE 32 IN A:94
STORE 32 IN A:95
STORE 83 IN A:96
STORE 85 IN A:97
STORE 66 IN A:98
STORE 45 IN A:99
STORE 80 IN A:100
STORE 82 IN A:101
STORE 79 IN A:102
STORE 67 IN A:103
STORE 69 IN A:104
STORE 68 IN A:105
STORE 85 IN A:106
STORE 82 IN A:107
STORE 69 IN A:108
STORE 32 IN A:109
STORE 83 IN A:110
STORE 72 IN A:111
STORE 79 IN A:112
STORE 87 IN A:113
STORE 85 IN A:114
STORE 10 IN A:115
STORE 32 IN A:116
STORE 32 IN A:117
STORE 32 IN A:118
STORE 32 IN A:119
STORE 83 IN A:120
STORE 84 IN A:121
STORE 79 IN A:122
STORE 82 IN A:123
STORE 69 IN A:124
STORE 32 IN A:125
STORE 48 IN A:126
STORE 32 IN A:127
STORE 73 IN A:128
STORE 78 IN A:129
STORE 32 IN A:130
STORE 73 IN A:131
STORE 10 IN A:132
STORE 32 IN A:133
STORE 32 IN A:134
STORE 32 IN A:135
STORE 32 IN A:136
STORE 87 IN A:137
STORE 72 IN A:138
STORE 73 IN A:139
STORE 76 IN A:140
STORE 69 IN A:141
STORE 32 IN A:142
STORE 73 IN A:143
STORE 32 IN A:144
STORE 73 IN A:145
STORE 83 IN A:146
STORE 32 IN A:147
STORE 76 IN A:148
STORE 69 IN A:149
STORE 83 IN A:150
STORE 83 IN A:151
STORE 32 IN A:152
STORE 84 IN A:153
STORE 72 IN A:154
STORE 65 IN A:155
STORE 78 IN A:156
STORE 32 IN A:157
STORE 78 IN A:158
STORE 32 IN A:159
STORE 68 IN A:160
STORE 79 IN A:161
STORE 10 IN A:162
STORE 32 IN A:163
STORE 32 IN A:164
STORE 32 IN A:165
STORE 32 IN A:166
STORE 32 IN A:167
STORE 32 IN A:168
STORE 32 IN A:169
STORE 32 IN A:170
STORE 68 IN A:171
STORE 73 IN A:172
STORE 83 IN A:173
STORE 80 IN A:174
STORE 76 IN A:175
STORE 65 IN A:176
STORE 89 IN A:177
STORE 32 IN A:178
STORE 34 IN A:179
STORE 32 IN A:180
STORE 32 IN A:181
STORE 83 IN A:182
STORE 84 IN A:183
STORE 79 IN A:184
STORE 82 IN A:185
STORE 69 IN A:186
STORE 32 IN A:187
STORE 34 IN A:188
STORE 10 IN A:189
STORE 32 IN A:190
STORE 32 IN A:191
STORE 32 IN A:192
STORE 32 IN A:193
STORE 32 IN A:194
STORE 32 IN A:195
STORE 32 IN A:196
STORE 32 IN A:197
STORE 68 IN A:198
STORE 73 IN A:199
STORE 83 IN A:200
STORE 80 IN A:201
STORE 76 IN A:202
STORE 65 IN A:203
STORE 89 IN A:204
STORE 32 IN A:205
STORE 65 IN A:206
STORE 58 IN A:207
STORE 73 IN A:208
STORE 10 IN A:209
STORE 32 IN A:210
STORE 32 IN A:211
STORE 32 IN A:212
STORE 32 IN A:213
STORE 32 IN A:214
STORE 32 IN A:215
STORE 32 IN A:216
STORE 32 IN A:217
STORE 68 IN A:218
STORE 73 IN A:219
STORE 83 IN A:220
STORE 80 IN A:221
STORE 76 IN A:222
STORE 65 IN A:223
STORE 89 IN A:224
STORE 32 IN A:225
STORE 34 IN A:226
STORE 32 IN A:227
STORE 73 IN A:228
STORE 78 IN A:229
STORE 32 IN A:230
STORE 34 IN A:231
STORE 10 IN A:232
STORE 32 IN A:233
STORE 32 IN A:234
STORE 32 IN A:235
STORE 32 IN A:236
STORE 32 IN A:237
STORE 32 IN A:238
STORE 32 IN A:239
STORE 32 IN A:240
STORE 68 IN A:241
STORE 73 IN A:242
STORE 83 IN A:243
STORE 80 IN A:244
STORE 76 IN A:245
STORE 65 IN A:246
STORE 89 IN A:247
STORE 32 IN A:248
STORE 34 IN A:249
STORE 32 IN A:250
STORE 65 IN A:251
STORE 58 IN A:252
STORE 34 IN A:253
STORE 10 IN A:254
STORE 32 IN A:255
STORE 32 IN A:256
STORE 32 IN A:257
STORE 32 IN A:258
STORE 32 IN A:259
STORE 32 IN A:260
STORE 32 IN A:261
STORE 32 IN A:262
STORE 68 IN A:263
STORE 73 IN A:264
STORE 83 IN A:265
STORE 80 IN A:266
STORE 76 IN A:267
STORE 65 IN A:268
STORE 89 IN A:269
STORE 32 IN A:270
STORE 73 IN A:271
STORE 32 IN A:272
STORE 67 IN A:273
STORE 82 IN A:274
STORE 76 IN A:275
STORE 70 IN A:276
STORE 10 IN A:277
STORE 32 IN A:278
STORE 32 IN A:279
STORE 32 IN A:280
STORE 32 IN A:281
STORE 32 IN A:282
STORE 32 IN A:283
STORE 32 IN A:284
STORE 32 IN A:285
STORE 65 IN A:286
STORE 68 IN A:287
STORE 68 IN A:288
STORE 32 IN A:289
STORE 73 IN A:290
STORE 32 IN A:291
STORE 65 IN A:292
STORE 78 IN A:293
STORE 68 IN A:294
STORE 32 IN A:295
STORE 49 IN A:296
STORE 32 IN A:297
STORE 73 IN A:298
STORE 78 IN A:299
STORE 32 IN A:300
STORE 73 IN A:301
STORE 10 IN A:302
STORE 32 IN A:303
STORE 32 IN A:304
STORE 32 IN A:305
STORE 32 IN A:306
STORE 82 IN A:307
STORE 69 IN A:308
STORE 80 IN A:309
STORE 69 IN A:310
STORE 65 IN A:311
STORE 84 IN A:312
STORE 10 IN A:313
STORE 32 IN A:314
STORE 32 IN A:315
STORE 32 IN A:316
STORE 32 IN A:317
STORE 68 IN A:318
STORE 73 IN A:319
STORE 83 IN A:320
STORE 80 IN A:321
STORE 76 IN A:322
STORE 65 IN A:323
STORE 89 IN A:324
STORE 32 IN A:325
STORE 34 IN A:326
STORE 32 IN A:327
STORE 32 IN A:328
STORE 83 IN A:329
STORE 84 IN A:330
STORE 79 IN A:331
STORE 82 IN A:332
STORE 69 IN A:333
STORE 32 IN A:334
STORE 34 IN A:335
STORE 10 IN A:336
STORE 32 IN A:337
STORE 32 IN A:338
STORE 32 IN A:339
STORE 32 IN A:340
STORE 68 IN A:341
STORE 73 IN A:342
STORE 83 IN A:343
STORE 80 IN A:344
STORE 76 IN A:345
STORE 65 IN A:346
STORE 89 IN A:347
STORE 32 IN A:348
STORE 78 IN A:349
STORE 10 IN A:350
STORE 32 IN A:351
STORE 32 IN A:352
STORE 32 IN A:353
STORE 32 IN A:354
STORE 68 IN A:355
STORE 73 IN A:356
STORE 83 IN A:357
STORE 80 IN A:358
STORE 76 IN A:359
STORE 65 IN A:360
STORE 89 IN A:361
STORE 32 IN A:362
STORE 34 IN A:363
STORE 32 IN A:364
STORE 73 IN A:365
STORE 78 IN A:366
STORE 32 IN A:367
STORE 78 IN A:368
STORE 34 IN A:369
STORE 32 IN A:370
STORE 67 IN A:371
STORE 82 IN A:372
STORE 76 IN A:373
STORE 70 IN A:374
STORE 10 IN A:375
STORE 32 IN A:376
STORE 32 IN A:377
STORE 69 IN A:378
STORE 78 IN A:379
STORE 68 IN A:380
STORE 32 IN A:381
STORE 83 IN A:382
STORE 85 IN A:383
STORE 66 IN A:384
STORE 45 IN A:385
STORE 80 IN A:386
STORE 82 IN A:387
STORE 79 IN A:388
STORE 67 IN A:389
STORE 69 IN A:390
STORE 68 IN A:391
STORE 85 IN A:392
STORE 82 IN A:393
STORE 69 IN A:394
STORE 10 IN A:395
STORE 10 IN A:396
STORE 32 IN A:397
STORE 32 IN A:398
STORE 83 IN A:399
STORE 85 IN A:400
STORE 66 IN A:401
STORE 45 IN A:402
STORE 80 IN A:403
STORE 82 IN A:404
STORE 79 IN A:405
STORE 67 IN A:406
STORE 69 IN A:407
STORE 68 IN A:408
STORE 85 IN A:409
STORE 82 IN A:410
STORE 69 IN A:411
STORE 32 IN A:412
STORE 83 IN A:413
STORE 72 IN A:414
STORE 79 IN A:415
STORE 87 IN A:416
STORE 10 IN A:417
STORE 32 IN A:418
STORE 32 IN A:419
STORE 32 IN A:420
STORE 32 IN A:421
STORE 83 IN A:422
STORE 84 IN A:423
STORE 79 IN A:424
STORE 82 IN A:425
STORE 69 IN A:426
STORE 32 IN A:427
STORE 48 IN A:428
STORE 32 IN A:429
STORE 73 IN A:430
STORE 78 IN A:431
STORE 32 IN A:432
STORE 74 IN A:433
STORE 10 IN A:434
STORE 32 IN A:435
STORE 32 IN A:436
STORE 32 IN A:437
STORE 32 IN A:438
STORE 87 IN A:439
STORE 72 IN A:440
STORE 73 IN A:441
STORE 76 IN A:442
STORE 69 IN A:443
STORE 32 IN A:444
STORE 74 IN A:445
STORE 32 IN A:446
STORE 73 IN A:447
STORE 83 IN A:448
STORE 32 IN A:449
STORE 76 IN A:450
STORE 69 IN A:451
STORE 83 IN A:452
STORE 83 IN A:453
STORE 32 IN A:454
STORE 84 IN A:455
STORE 72 IN A:456
STORE 65 IN A:457
STORE 78 IN A:458
STORE 32 IN A:459
STORE 78 IN A:460
STORE 32 IN A:461
STORE 68 IN A:462
STORE 79 IN A:463
STORE 10 IN A:464
STORE 32 IN A:465
STORE 32 IN A:466
STORE 32 IN A:467
STORE 32 IN A:468
STORE 32 IN A:469
STORE 32 IN A:470
STORE 32 IN A:471
STORE 32 IN A:472
STORE 73 IN A:473
STORE 70 IN A:474
STORE 32 IN A:475
STORE 65 IN A:476
STORE 58 IN A:477
STORE 74 IN A:478
STORE 32 IN A:479
STORE 73 IN A:480
STORE 83 IN A:481
STORE 32 IN A:482
STORE 69 IN A:483
STORE 81 IN A:484
STORE 85 IN A:485
STORE 65 IN A:486
STORE 76 IN A:487
STORE 32 IN A:488
STORE 84 IN A:489
STORE 79 IN A:490
STORE 32 IN A:491
STORE 52 IN A:492
STORE 50 IN A:493
STORE 32 IN A:494
STORE 84 IN A:495
STORE 72 IN A:496
STORE 69 IN A:497
STORE 78 IN A:498
STORE 10 IN A:499
STORE 32 IN A:500
STORE 32 IN A:501
STORE 32 IN A:502
STORE 32 IN A:503
STORE 32 IN A:504
STORE 32 IN A:505
STORE 32 IN A:506
STORE 32 IN A:507
STORE 32 IN A:508
STORE 32 IN A:509
STORE 67 IN A:510
STORE 65 IN A:511
STORE 76 IN A:512
STORE 76 IN A:513
STORE 32 IN A:514
STORE 83 IN A:515
STORE 85 IN A:516
STORE 66 IN A:517
STORE 45 IN A:518
STORE 80 IN A:519
STORE 82 IN A:520
STORE 79 IN A:521
STORE 67 IN A:522
STORE 69 IN A:523
STORE 68 IN A:524
STORE 85 IN A:525
STORE 82 IN A:526
STORE 69 IN A:527
STORE 32 IN A:528
STORE 83 IN A:529
STORE 72 IN A:530
STORE 79 IN A:531
STORE 87 IN A:532
STORE 85 IN A:533
STORE 10 IN A:534
STORE 32 IN A:535
STORE 32 IN A:536
STORE 32 IN A:537
STORE 32 IN A:538
STORE 32 IN A:539
STORE 32 IN A:540
STORE 32 IN A:541
STORE 32 IN A:542
STORE 69 IN A:543
STORE 76 IN A:544
STORE 83 IN A:545
STORE 69 IN A:546
STORE 10 IN A:547
STORE 32 IN A:548
STORE 32 IN A:549
STORE 32 IN A:550
STORE 32 IN A:551
STORE 32 IN A:552
STORE 32 IN A:553
STORE 32 IN A:554
STORE 32 IN A:555
STORE 32 IN A:556
STORE 32 IN A:557
STORE 83 IN A:558
STORE 84 IN A:559
STORE 79 IN A:560
STORE 82 IN A:561
STORE 69 IN A:562
STORE 32 IN A:563
STORE 67 IN A:564
STORE 72 IN A:565
STORE 65 IN A:566
STORE 82 IN A:567
STORE 65 IN A:568
STORE 67 IN A:569
STORE 84 IN A:570
STORE 69 IN A:571
STORE 82 IN A:572
STORE 32 IN A:573
STORE 65 IN A:574
STORE 58 IN A:575
STORE 74 IN A:576
STORE 32 IN A:577
STORE 73 IN A:578
STORE 78 IN A:579
STORE 32 IN A:580
STORE 67 IN A:581
STORE 10 IN A:582
STORE 32 IN A:583
STORE 32 IN A:584
STORE 32 IN A:585
STORE 32 IN A:586
STORE 32 IN A:587
STORE 32 IN A:588
STORE 32 IN A:589
STORE 32 IN A:590
STORE 32 IN A:591
STORE 32 IN A:592
STORE 68 IN A:593
STORE 73 IN A:594
STORE 83 IN A:595
STORE 80 IN A:596
STORE 76 IN A:597
STORE 65 IN A:598
STORE 89 IN A:599
STORE 32 IN A:600
STORE 67 IN A:601
STORE 10 IN A:602
STORE 32 IN A:603
STORE 32 IN A:604
STORE 32 IN A:605
STORE 32 IN A:606
STORE 32 IN A:607
STORE 32 IN A:608
STORE 32 IN A:609
STORE 32 IN A:610
STORE 69 IN A:611
STORE 78 IN A:612
STORE 68 IN A:613
STORE 45 IN A:614
STORE 73 IN A:615
STORE 70 IN A:616
STORE 10 IN A:617
STORE 32 IN A:618
STORE 32 IN A:619
STORE 32 IN A:620
STORE 32 IN A:621
STORE 32 IN A:622
STORE 32 IN A:623
STORE 32 IN A:624
STORE 32 IN A:625
STORE 65 IN A:626
STORE 68 IN A:627
STORE 68 IN A:628
STORE 32 IN A:629
STORE 74 IN A:630
STORE 32 IN A:631
STORE 65 IN A:632
STORE 78 IN A:633
STORE 68 IN A:634
STORE 32 IN A:635
STORE 49 IN A:636
STORE 32 IN A:637
STORE 73 IN A:638
STORE 78 IN A:639
STORE 32 IN A:640
STORE 74 IN A:641
STORE 10 IN A:642
STORE 32 IN A:643
STORE 32 IN A:644
STORE 32 IN A:645
STORE 32 IN A:646
STORE 82 IN A:647
STORE 69 IN A:648
STORE 80 IN A:649
STORE 69 IN A:650
STORE 65 IN A:651
STORE 84 IN A:652
STORE 10 IN A:653
STORE 32 IN A:654
STORE 32 IN A:655
STORE 69 IN A:656
STORE 78 IN A:657
STORE 68 IN A:658
STORE 32 IN A:659
STORE 83 IN A:660
STORE 85 IN A:661
STORE 66 IN A:662
STORE 45 IN A:663
STORE 80 IN A:664
STORE 82 IN A:665
STORE 79 IN A:666
STORE 67 IN A:667
STORE 69 IN A:668
STORE 68 IN A:669
STORE 85 IN A:670
STORE 82 IN A:671
STORE 69 IN A:672
STORE 10 IN A:673
STORE 10 IN A:674
STORE 42 IN A:675
STORE 10 IN A:676
STORE 32 IN A:677
STORE 32 IN A:678
STORE 67 IN A:679
STORE 65 IN A:680
STORE 76 IN A:681
STORE 76 IN A:682
STORE 32 IN A:683
STORE 83 IN A:684
STORE 85 IN A:685
STORE 66 IN A:686
STORE 45 IN A:687
STORE 80 IN A:688
STORE 82 IN A:689
STORE 79 IN A:690
STORE 67 IN A:691
STORE 69 IN A:692
STORE 68 IN A:693
STORE 85 IN A:694
STORE 82 IN A:695
STORE 69 IN A:696
STORE 32 IN A:697
STORE 83 IN A:698
STORE 72 IN A:699
STORE 79 IN A:700
STORE 87 IN A:701
STORE 10 IN A:702
STORE 10 IN A:703
STORE 704 IN N
CALL SUB-PROCEDURE SHOW |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT,{}
MODE DATA
$$ numbers=*
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
$$ MODE TUSCRIPT
numbers=EXCHANGE (numbers,":,{0-00} :':")
unrangednrs=JOIN (numbers,"")
rangednrs=COMBINE (unrangednrs,"")
rangednrs=EXCHANGE (rangednrs,":':,:")
PRINT rangednrs
|
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Wren | Wren | import "/str" for Str
import "/upc" for Graphemes
for (word in ["asdf", "josé", "møøse", "was it a car or a cat I saw", "😀🚂🦊"]) {
System.print(Str.reverse(word))
}
for (word in ["as⃝df̅", "ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧 👨👩👧👦🆗🗺"]) {
System.print(Graphemes.new(word).toList[-1..0].join())
} |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ring | Ring |
# Project : Queue/Definition
load "stdlib.ring"
oQueue = new Queue
for n = 5 to 7
see "Push: " + n + nl
oQueue.add(n)
next
see "Pop: " + oQueue.remove() + nl
see "Push: 8" + nl
oQueue.add(8)
see "Pop: " + oQueue.remove() + nl
see "Pop: " + oQueue.remove() + nl
see "Pop: " + oQueue.remove() + nl
if len(oQueue) != 0
oQueue.print()
else
see "Error: queue is empty" + nl
ok
|
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Liberty_BASIC | Liberty BASIC | s$ = "s$ = : Print Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 5)" : Print Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 5) |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
| #TXR | TXR | (defun range-extract (numbers)
`@{(mapcar [iff [callf > length (ret 2)]
(ret `@[@1 0]-@[@1 -1]`)
(ret `@{@1 ","}`)]
(mapcar (op mapcar car)
(split [window-map 1 :reflect
(op list @2 (- @2 @1))
(sort (uniq numbers))]
(op where [chain second (op < 1)])))) ","}`) |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Wortel | Wortel | ; the @rev operator reverses strings and arrays
@rev "abc" ; returns "cba"
; or the same thing using a pointer expression
!~r "abc" |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ruby | Ruby | require 'forwardable'
# A FIFO queue contains elements in first-in, first-out order.
# FIFO#push adds new elements to the end of the queue;
# FIFO#pop or FIFO#shift removes elements from the front.
class FIFO
extend Forwardable
# Creates a FIFO containing _objects_.
def self.[](*objects)
new.push(*objects)
end
# Creates an empty FIFO.
def initialize; @ary = []; end
# Appends _objects_ to the end of this FIFO. Returns self.
def push(*objects)
@ary.push(*objects)
self
end
alias << push
alias enqueue push
##
# :method: pop
# :call-seq:
# pop -> obj or nil
# pop(n) -> ary
#
# Removes an element from the front of this FIFO, and returns it.
# Returns nil if the FIFO is empty.
#
# If passing a number _n_, removes the first _n_ elements, and returns
# an Array of them. If this FIFO contains fewer than _n_ elements,
# returns them all. If this FIFO is empty, returns an empty Array.
def_delegator :@ary, :shift, :pop
alias shift pop
alias dequeue shift
##
# :method: empty?
# Returns true if this FIFO contains no elements.
def_delegator :@ary, :empty?
##
# :method: size
# Returns the number of elements in this FIFO.
def_delegator :@ary, :size
alias length size
# Converts this FIFO to a String.
def to_s
"FIFO#{@ary.inspect}"
end
alias inspect to_s
end |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #LIL | LIL | # reflect this
reflect this |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
| #UNIX_Shell | UNIX Shell | #!/usr/bin/bash
range_contract () (
add_range () {
case $(( current - range_start )) in
0) ranges+=( $range_start ) ;;
1) ranges+=( $range_start $current ) ;;
*) ranges+=("$range_start-$current") ;;
esac
}
ranges=()
range_start=$1
current=$1
shift
for number; do
if (( number > current+1 )); then
add_range
range_start=$number
fi
current=$number
done
add_range
x="${ranges[@]}"
echo ${x// /,}
)
range_contract 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #XBS | XBS | log(string.reverse("Hello")) |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Rust | Rust | use std::collections::VecDeque;
fn main() {
let mut stack = VecDeque::new();
stack.push_back("Element1");
stack.push_back("Element2");
stack.push_back("Element3");
assert_eq!(Some(&"Element1"), stack.front());
assert_eq!(Some("Element1"), stack.pop_front());
assert_eq!(Some("Element2"), stack.pop_front());
assert_eq!(Some("Element3"), stack.pop_front());
assert_eq!(None, stack.pop_front());
} |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Lisp | Lisp | ((lambda (x) (list x (list 'quote x)))
'(lambda (x) (list x (list 'quote x)))) |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
| #Ursala | Ursala | #import std
#import int
x = <0,1,2,4,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,32,33,35,36,37,38,39>
f = mat`,+ ==?(~&l,^|T/~& :/`-)*bhPS+ %zP~~hzX*titZBPiNCSiNCQSL+ rlc ^|E/~& predecessor
#show+
t = <f x> |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings, instead of MSb terminated
func StrLen(Str); \Return the number of characters in an ASCIIZ string
char Str;
int I;
for I:= 0 to -1>>1-1 do
if Str(I) = 0 then return I;
func RevStr(S); \Reverse the order of the bytes in a string
char S;
int L, I, T;
[L:= StrLen(S);
for I:= 0 to L/2-1 do
[T:= S(I); S(I):= S(L-I-1); S(L-I-1):= T];
return S;
];
[Text(0, RevStr("a")); CrLf(0);
Text(0, RevStr("ab")); CrLf(0);
Text(0, RevStr("abc")); CrLf(0);
Text(0, RevStr("Able was I ere I saw Elba.")); CrLf(0);
] |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Scala | Scala | class Queue[T] {
private[this] class Node[T](val value:T) {
var next:Option[Node[T]]=None
def append(n:Node[T])=next=Some(n)
}
private[this] var head:Option[Node[T]]=None
private[this] var tail:Option[Node[T]]=None
def isEmpty=head.isEmpty
def enqueue(item:T)={
val n=new Node(item)
if(isEmpty) head=Some(n) else tail.get.append(n)
tail=Some(n)
}
def dequeue:T=head match {
case Some(item) => head=item.next; item.value
case None => throw new java.util.NoSuchElementException()
}
def front:T=head match {
case Some(item) => item.value
case None => throw new java.util.NoSuchElementException()
}
def iterator: Iterator[T]=new Iterator[T]{
private[this] var it=head;
override def hasNext=it.isDefined
override def next:T={val n=it.get; it=n.next; n.value}
}
override def toString()=iterator.mkString("Queue(", ", ", ")")
} |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Logo | Logo | make "a [ 116 121 112 101 32 34 124 109 97 107 101 32 34 97 32 91 124 10 102 111 114 101 97 99 104 32 58 97 32 91 32 116 121 112 101 32 119 111 114 100 32 34 124 32 124 32 63 32 93 10 112 114 105 110 116 32 34 124 32 93 124 10 102 111 114 101 97 99 104 32 58 97 32 91 32 116 121 112 101 32 99 104 97 114 32 63 32 93 10 98 121 101 10 ]
type "|make "a [|
foreach :a [ type word "| | ? ]
print "| ]|
foreach :a [ type char ? ]
bye |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
| #VBA | VBA |
Public Function RangeExtraction(AList) As String
'AList is a variant that is an array, assumed filled with numbers in ascending order
Const RangeDelim = "-" 'range delimiter
Dim result As String
Dim InRange As Boolean
Dim Posn, ub, lb, rangestart, rangelen As Integer
result = ""
'find dimensions of AList
ub = UBound(AList)
lb = LBound(AList)
Posn = lb
While Posn < ub
rangestart = Posn
rangelen = 0
InRange = True
'try to extend the range
While InRange
rangelen = rangelen + 1
If Posn = ub Then
InRange = False
Else
InRange = (AList(Posn + 1) = AList(Posn) + 1)
Posn = Posn + 1
End If
Wend
If rangelen > 2 Then 'output the range if it has more than 2 elements
result = result & "," & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))
Else 'output the separate elements
For i = rangestart To rangestart + rangelen - 1
result = result & "," & Format$(AList(i))
Next
End If
Posn = rangestart + rangelen
Wend
RangeExtraction = Mid$(result, 2) 'get rid of first comma!
End Function
Public Sub RangeTest()
'test function RangeExtraction
'first test with a Variant array
Dim MyList As Variant
MyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)
Debug.Print "a) "; RangeExtraction(MyList)
'next test with an array of integers
Dim MyOtherList(1 To 20) As Integer
MyOtherList(1) = -6
MyOtherList(2) = -3
MyOtherList(3) = -2
MyOtherList(4) = -1
MyOtherList(5) = 0
MyOtherList(6) = 1
MyOtherList(7) = 3
MyOtherList(8) = 4
MyOtherList(9) = 5
MyOtherList(10) = 7
MyOtherList(11) = 8
MyOtherList(12) = 9
MyOtherList(13) = 10
MyOtherList(14) = 11
MyOtherList(15) = 14
MyOtherList(16) = 15
MyOtherList(17) = 17
MyOtherList(18) = 18
MyOtherList(19) = 19
MyOtherList(20) = 20
Debug.Print "b) "; RangeExtraction(MyOtherList)
End Sub
|
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Yorick | Yorick | strchar(strchar("asdf")(:-1)(::-1)) |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Scheme | Scheme | (define (make-queue)
(make-vector 1 '()))
(define (push a queue)
(vector-set! queue 0 (append (vector-ref queue 0) (list a))))
(define (empty? queue)
(null? (vector-ref queue 0)))
(define (pop queue)
(if (empty? queue)
(error "can not pop an empty queue")
(let ((ret (car (vector-ref queue 0))))
(vector-set! queue 0 (cdr (vector-ref queue 0)))
ret)))
|
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Lua | Lua | s=[[io.write('s=[','[',s,']','];',s)]];io.write('s=[','[',s,']','];',s) |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
| #VBScript | VBScript | Function Range_Extraction(list)
num = Split(list,",")
For i = 0 To UBound(num)
startnum = CInt(num(i))
sum = startnum
Do While i <= UBound(num)
If sum = CInt(num(i)) Then
If i = UBound(num) Then
If startnum <> CInt(num(i)) Then
If startnum + 1 = CInt(num(i)) Then
Range_Extraction = Range_Extraction & startnum & "," & num(i) & ","
Else
Range_Extraction = Range_Extraction & startnum & "-" & num(i) & ","
End If
Else
Range_Extraction = Range_Extraction & startnum & ","
End If
Exit Do
Else
i = i + 1
sum = sum + 1
End If
Else
If startnum = CInt(num(i-1)) Then
Range_Extraction = Range_Extraction & startnum & ","
Else
If startnum + 1 = CInt(num(i-1)) Then
Range_Extraction = Range_Extraction & startnum & "," & num(i-1) & ","
Else
Range_Extraction = Range_Extraction & startnum & "-" & num(i-1) & ","
End If
End If
i = i - 1
Exit Do
End If
Loop
Next
Range_Extraction = Left(Range_Extraction,Len(Range_Extraction)-1)
End Function
WScript.StdOut.Write Range_Extraction("0,1,2,4,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,32,33,35,36,37,38,39") |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Z80_Assembly | Z80 Assembly | PrintChar equ $BB5A ;Amstrad CPC bios call
Terminator equ 0 ;null terminator for strings
org $8000
ld hl, StringA
call ReverseString
ld hl, StringA
call PrintString
ret ;return to basic
StringA:
byte "12345678",0
;;;; SUBROUTINES
GetStringLength:
;HL = STRING. RETURNS LENGTH IN B. LENGTH IS ONE-INDEXED AND DOES NOT INCLUDE TERMINATOR.
ld b,0 ;clear B
loop_getStringLength:
ld a,(hl) ;read the next char
cp Terminator ;is it the terminator?
ret z ;if so, exit
inc hl ;point HL to next character
inc b ;increase tally
jr loop_getStringLength ;repeat
ReverseString:
;reverse the order of letters in a text string.
;e.g. "ABCD" -> "DCBA"
;the terminator stays put.
;INPUT: HL = SOURCE ADDRESS OF STRING
push de
push hl
push hl
call GetStringLength
pop hl
pop de ;LD DE,HL
LD a,b ;LOAD B INTO A
LD (SMC_ReverseString+1),a ;STORE IT LATER IN THE CODE SO WE CAN RETRIEVE IT.
; TO RECAP, BOTH HL AND DE POINT TO THE BEGINNING OF THE STRING WE WANT TO REVERSE. B EQUALS THE LENGTH OF THE STRING.
; B HAS BEEN BACKED UP WITHOUT USING THE STACK BY STORING IT AS THE OPERAND OF A LATER INSTRUCTION THAT LOADS B WITH A NUMERIC VALUE.
; PUSH BC WOULD NOT HAVE WORKED SINCE THE PROGRAM NEEDS TO PUSH EACH LETTER OF THE STRING DURING THE LOOP.
LOOP_REVERSESTRING_PUSH:
;start at the beginning of the string and push each letter in it, except the terminator.
ld a,(de)
push af
inc de
djnz LOOP_REVERSESTRING_PUSH
SMC_ReverseString:
ld b,$42 ;LETS US PRESERVE B WITHOUT PUSHING IT. THE $42 IS OVERWRITTEN WITH THE STRING'S LENGTH.
LOOP_REVERSESTRING_POP:
;Starting at the beginning of the string, pop A off the stack and store it into the string. This puts the letters back in the reverse
; order.
pop af
ld (hl),a
inc hl
djnz LOOP_REVERSESTRING_POP
pop de
ret |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #SenseTalk | SenseTalk |
set myFoods to be an empty list
push "grapes" into myFoods
push "orange" into myFoods
push "apricot" into myFoods
put "The foods in my queue are: " & myFoods
pull from myFoods into firstThingToEat
put "The first thing to eat is: " & firstThingToEat
if myFoods is empty then
put "The foods list is empty!"
else
put "The remaining foods are: " & myFoods
end if
|
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #M2000_Interpreter | M2000 Interpreter |
Module Alfa {
Rem {This Program Show itself in Help Form}
inline "help "+quote$(module.name$)
}
Alfa
|
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
| #Wren | Wren | var extractRange = Fn.new { |list|
if (list.isEmpty) return ""
var sb = ""
var first = list[0]
var prev = first
var append = Fn.new { |index|
if (first == prev) {
sb = sb + prev.toString
} else if (first == prev - 1) {
sb = sb + first.toString + "," + prev.toString
} else {
sb = sb + first.toString + "-" + prev.toString
}
if (index < list.count - 1) sb = sb + ","
}
for (i in 1...list.count) {
if (list[i] == prev + 1) {
prev = prev + 1
} else {
append.call(i)
first = list[i]
prev = first
}
}
append.call(list.count - 1)
return sb
}
var list1 = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]
System.print(extractRange.call(list1))
var list2 = [0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39]
System.print(extractRange.call(list2)) |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #zkl | zkl | "this is a test".reverse() |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Sidef | Sidef | class FIFO(*array) {
method pop {
array.is_empty && die "underflow";
array.shift;
}
method push(*items) {
array += items;
self;
}
method empty {
array.len == 0;
}
} |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #M4 | M4 | define(`quine',``$1(`$1')'')dnl
quine(`define(`quine',``$1(`$1')'')dnl
quine') |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
| #zkl | zkl | fcn range(ns){
fcn(w){
if (w.atEnd) return(Void.Stop);
a:=b:=w.next(); n:=0;
while(b+1 == (c:=w.peekN(n))){ n+=1; b=c }
if(n>1){do(n){w.next()}; return("%d-%d".fmt(a,b)); }
a
} :
(0).pump(*,List,_.fp(ns.walker().tweak(Void,Void))).concat(",");
} |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Zoea | Zoea |
program: reverse_string
input: xyzzy
output: yzzyx
|
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Slate | Slate | collections define: #Queue &parents: {ExtensibleArray}.
q@(Queue traits) isEmpty [resend].
q@(Queue traits) push: obj [q addLast: obj].
q@(Queue traits) pop [q removeFirst].
q@(Queue traits) pushAll: c [q addAllLast: c].
q@(Queue traits) pop: n [q removeFirst: n]. |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | a="Print[\"a=\",InputForm[a],\";\",a]";Print["a=",InputForm[a],";",a] |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Zoea_Visual | Zoea Visual |
var s = "socat".*;
std.mem.reverse(u8, &s);
|
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Smalltalk | Smalltalk | OrderedCollection extend [
push: obj [ ^(self add: obj) ]
pop [
(self isEmpty) ifTrue: [
SystemExceptions.NotFound signalOn: self
reason: 'queue empty'
] ifFalse: [
^(self removeFirst)
]
]
]
|f|
f := OrderedCollection new.
f push: 'example'; push: 'another'; push: 'last'.
f pop printNl.
f pop printNl.
f pop printNl.
f isEmpty printNl.
f pop. "queue empty error" |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #MATLAB_.2F_Octave | MATLAB / Octave | x='{>\(y>(((-y-(((<(^<ejtq)\{-y.2^*<';z=['x=''',x,''';'];disp([z,x-1]); |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Zig | Zig |
var s = "socat".*;
std.mem.reverse(u8, &s);
|
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Standard_ML | Standard ML |
signature QUEUE =
sig
type 'a queue
val empty_queue: 'a queue
exception Empty
val enq: 'a queue -> 'a -> 'a queue
val deq: 'a queue -> ('a * 'a queue)
val empty: 'a queue -> bool
end;
|
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Stata | Stata | proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
}
proc pop {stackvar} {
upvar 1 $stackvar stack
set value [lindex $stack 0]
set stack [lrange $stack 1 end]
return $value
}
proc size {stackvar} {
upvar 1 $stackvar stack
llength $stack
}
proc empty {stackvar} {
upvar 1 $stackvar stack
expr {[size stack] == 0}
}
proc peek {stackvar} {
upvar 1 $stackvar stack
lindex $stack 0
}
set Q [list]
empty Q ;# ==> 1 (true)
push Q foo
empty Q ;# ==> 0 (false)
push Q bar
peek Q ;# ==> foo
pop Q ;# ==> foo
peek Q ;# ==> bar |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Maxima | Maxima | /* Using ?format from the unerlying Lisp system */
lambda([],block([q:ascii(34),s:"lambda([],block([q:ascii(34),s:~A~A~A],print(?format(false,s,q,s,q))))()$"],print(?format(false,s,q,s,q))))()$ |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Tcl | Tcl | proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
}
proc pop {stackvar} {
upvar 1 $stackvar stack
set value [lindex $stack 0]
set stack [lrange $stack 1 end]
return $value
}
proc size {stackvar} {
upvar 1 $stackvar stack
llength $stack
}
proc empty {stackvar} {
upvar 1 $stackvar stack
expr {[size stack] == 0}
}
proc peek {stackvar} {
upvar 1 $stackvar stack
lindex $stack 0
}
set Q [list]
empty Q ;# ==> 1 (true)
push Q foo
empty Q ;# ==> 0 (false)
push Q bar
peek Q ;# ==> foo
pop Q ;# ==> foo
peek Q ;# ==> bar |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #MiniScript | MiniScript | s="s=;print s[:2]+char(34)+s+char(34)+s[2:]";print s[:2]+char(34)+s+char(34)+s[2:] |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #UNIX_Shell | UNIX Shell | queue_push() {
typeset -n q=$1
shift
q+=("$@")
}
queue_pop() {
if queue_empty $1; then
print -u2 "queue $1 is empty"
return 1
fi
typeset -n q=$1
print "${q[0]}" # emit the value of the popped element
q=( "${q[@]:1}" ) # and remove the first element from the queue
}
queue_empty() {
typeset -n q=$1
(( ${#q[@]} == 0 ))
}
queue_peek() {
typeset -n q=$1
print "${q[0]}"
} |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #11l | 11l | T XorShiftStar
UInt64 state
F seed(seed_state)
.state = seed_state
F next_int() -> UInt32
V x = .state
x (+)= x >> 12
x (+)= x << 25
x (+)= x >> 27
.state = x
R (x * 2545'F491'4F6C'DD1D) >> 32
F next_float()
R Float(.next_int()) / 2.0^32
V random_gen = XorShiftStar()
random_gen.seed(1234567)
L 5
print(random_gen.next_int())
random_gen.seed(987654321)
V hist = Dict(0.<5, i -> (i, 0))
L 100'000
hist[Int(random_gen.next_float() * 5)]++
print(hist) |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Modula-2 | Modula-2 | MODULE Quine;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
CONST src = "MODULE Quine;\nFROM FormatString IMPORT FormatString;\nFROM Terminal IMPORT WriteString,ReadChar;\n\nCONST src = \x022%s\x022;\nVAR buf : ARRAY[0..2048] OF CHAR;\nBEGIN\n FormatString(src, buf, src);\n WriteString(buf);\n ReadChar\nEND Quine.\n";
VAR buf : ARRAY[0..2048] OF CHAR;
BEGIN
FormatString(src, buf, src);
WriteString(buf);
ReadChar
END Quine. |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #UnixPipes | UnixPipes | init() {echo > fifo}
push() {echo $1 >> fifo }
pop() {head -1 fifo ; (cat fifo | tail -n +2)|sponge fifo}
empty() {cat fifo | wc -l} |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #Ada | Ada | with Interfaces; use Interfaces;
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
const : constant Unsigned_64 := 16#2545_F491_4F6C_DD1D#;
state : Unsigned_64 := 0;
Unseeded_Error : exception;
procedure seed (num : Unsigned_64) is
begin
state := num;
end seed;
function Next_Int return Unsigned_32 is
x : Unsigned_64 := state;
begin
if state = 0 then
raise Unseeded_Error;
end if;
x := x xor (x / 2**12);
x := x xor (x * 2**25);
x := x xor (x / 2**27);
state := x;
return Unsigned_32 ((x * const) / 2**32);
end Next_Int;
function Next_Float return Long_Float is
begin
return Long_Float (Next_Int) / 2.0**32;
end Next_Float;
counts : array (0 .. 4) of Natural := (others => 0);
J : Natural;
begin
seed (1_234_567);
for I in 1 .. 5 loop
Put_Line (Unsigned_32'Image (Next_Int));
end loop;
seed (987_654_321);
for I in 1 .. 100_000 loop
J := Natural (Long_Float'Floor (Next_Float * 5.0));
counts (J) := counts (J) + 1;
end loop;
New_Line;
for I in counts'Range loop
Put_Line (I'Image & " :" & counts (I)'Image);
end loop;
end Main;
|
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #MUMPS | MUMPS | QUINE
NEW I,L SET I=0
FOR SET I=I+1,L=$TEXT(+I) Q:L="" WRITE $TEXT(+I),!
KILL I,L
QUIT
SMALL
S %=0 F W $T(+$I(%)),! Q:$T(+%)="" |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #NASM | NASM | %define a "%define "
%define b "db "
%define c "%deftok "
%define d "a, 97, 32, 34, a, 34, 10, a, 98, 32, 34, b, 34, 10, a, 99, 32, 34, c, 34, 10, a, 100, 32, 34, d, 34, 10, c, 101, 32, 100, 10, b, 101, 10"
%deftok e d
db e |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #V | V | [fifo_create []].
[fifo_push swap cons].
[fifo_pop [[*rest a] : [*rest] a] view].
[fifo_empty? dup empty?]. |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #VBA | VBA | Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #ALGOL_68 | ALGOL 68 | BEGIN # generate some pseudo random numbers using Xorshift star #
# note that although LONG INT is 64 bits in Algol 68G, LONG BITS is longer than 64 bits #
LONG BITS state;
LONG INT const = ABS LONG 16r2545f4914f6cdd1d;
LONG INT one shl 32 = ABS ( LONG 16r1 SHL 32 );
# sets the state to the specified seed value #
PROC seed = ( LONG INT num )VOID: state := BIN num;
# XOR and assign convenience operator #
PRIO XORAB = 1;
OP XORAB = ( REF LONG BITS x, LONG BITS v )REF LONG BITS: x := ( x XOR v ) AND LONG 16rffffffffffffffff;
# gets the next pseudo random integer #
PROC next int = LONG INT:
BEGIN
LONG BITS x := state;
x XORAB ( x SHR 12 );
x XORAB ( x SHL 25 );
x XORAB ( x SHR 27 );
state := x;
SHORTEN ABS ( 16rffffffff AND BIN ( ABS x * LENG const ) SHR 32 )
END # next int # ;
# gets the next pseudo random real #
PROC next float = LONG REAL: next int / one shl 32;
BEGIN # task test cases #
seed( 1234567 );
print( ( whole( next int, 0 ), newline ) ); # 3540625527 #
print( ( whole( next int, 0 ), newline ) ); # 2750739987 #
print( ( whole( next int, 0 ), newline ) ); # 4037983143 #
print( ( whole( next int, 0 ), newline ) ); # 1993361440 #
print( ( whole( next int, 0 ), newline ) ); # 3809424708 #
# count the number of occurances of 0..4 in a sequence of pseudo random reals scaled to be in [0..5) #
seed( 987654321 );
[ 0 : 4 ]INT counts; FOR i FROM LWB counts TO UPB counts DO counts[ i ] := 0 OD;
TO 100 000 DO counts[ SHORTEN ENTIER ( next float * 5 ) ] +:= 1 OD;
FOR i FROM LWB counts TO UPB counts DO
print( ( whole( i, -2 ), ": ", whole( counts[ i ], -6 ) ) )
OD;
print( ( newline ) )
END
END |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
Q = "'"
S = "\\"
N = "\n"
A = "&"
code = [ -
'/* NetRexx */', -
'options replace format comments java crossref savelog symbols nobinary', -
'', -
'Q = "&QS"', -
'S = "&ESC"', -
'N = "&NL"', -
'A = "&"', -
'code = [ -', -
'&REP', -
' ]', -
'', -
'pgm = ""', -
'txt = ""', -
'loop t_ = 0 for code.length', -
' txt = txt || " " || Q || code[t_] || Q || ", -" || N', -
' end t_', -
'txt = txt.strip("T", N)', -
'txt = txt.delstr(txt.lastpos(","), 1)', -
'', -
'K = ""', -
'K[0] = 5', -
'K[1] = A"NL"', -
'K[2] = A"AMP"', -
'K[3] = A"ESC"', -
'K[4] = A"QS"', -
'K[5] = A"REP"', -
'loop c_ = 0 for code.length', -
' loop v_ = 1 to K[0]', -
' T = K[v_]', -
' if code[c_].pos(T) <> 0 then do', -
' parse code[c_] pre(T)post', -
' select case T', -
' when K[1] then do', -
' code[c_] = pre || S || "n" || post', -
' end', -
' when K[2] then do', -
' code[c_] = pre || A || post', -
' end', -
' when K[3] then do', -
' code[c_] = pre || S || S || post', -
' end', -
' when K[4] then do', -
' code[c_] = pre || Q || post', -
' end', -
' when K[5] then do', -
' code[c_] = txt', -
' end', -
' otherwise nop', -
' end', -
' end', -
' end v_', -
' pgm = pgm || code[c_].strip("T") || N', -
' end c_', -
'pgm = pgm.strip("T", N) || N', -
'say pgm', -
'', -
'return', -
'' -
]
pgm = ""
txt = ""
loop t_ = 0 for code.length
txt = txt || " " || Q || code[t_] || Q || ", -" || N
end t_
txt = txt.strip("T", N)
txt = txt.delstr(txt.lastpos(","), 1)
K = ""
K[0] = 5
K[1] = A"NL"
K[2] = A"AMP"
K[3] = A"ESC"
K[4] = A"QS"
K[5] = A"REP"
loop c_ = 0 for code.length
loop v_ = 1 to K[0]
T = K[v_]
if code[c_].pos(T) <> 0 then do
parse code[c_] pre(T)post
select case T
when K[1] then do
code[c_] = pre || S || "n" || post
end
when K[2] then do
code[c_] = pre || A || post
end
when K[3] then do
code[c_] = pre || S || S || post
end
when K[4] then do
code[c_] = pre || Q || post
end
when K[5] then do
code[c_] = txt
end
otherwise nop
end
end
end v_
pgm = pgm || code[c_].strip("T") || N
end c_
pgm = pgm.strip("T", N) || N
say pgm
return |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #VBScript | VBScript | ' Queue Definition - VBScript
Option Explicit
Dim queue, i, x
Set queue = CreateObject("System.Collections.ArrayList")
If Not empty_(queue) Then Wscript.Echo queue.Count
push queue, "Banana"
push queue, "Apple"
push queue, "Pear"
push queue, "Strawberry"
Wscript.Echo "Count=" & queue.Count
Wscript.Echo pull(queue) & " - Count=" & queue.Count '
Wscript.Echo "Head=" & queue.Item(0)
Wscript.Echo "Tail=" & queue.Item(queue.Count-1)
Wscript.Echo queue.IndexOf("Pear", 0)
For i=1 To queue.Count
Wscript.Echo join(queue.ToArray(), ", ")
x = pull(queue)
Next 'i
Sub push(q, what)
q.Add what
End Sub 'push
Function pull(q)
Dim what
If q.Count > 0 Then
what = q(0)
q.RemoveAt 0
Else
what = ""
End If
pull = what
End Function 'pull
Function empty_(q)
empty_ = q.Count = 0
End Function 'empty_
|
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #C | C | #include <math.h>
#include <stdint.h>
#include <stdio.h>
static uint64_t state;
static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;
void seed(uint64_t num) {
state = num;
}
uint32_t next_int() {
uint64_t x;
uint32_t answer;
x = state;
x = x ^ (x >> 12);
x = x ^ (x << 25);
x = x ^ (x >> 27);
state = x;
answer = ((x * STATE_MAGIC) >> 32);
return answer;
}
float next_float() {
return (float)next_int() / (1LL << 32);
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
seed(1234567);
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("\n");
seed(987654321);
for (i = 0; i < 100000; i++) {
int j = (int)floor(next_float() * 5.0);
counts[j]++;
}
for (i = 0; i < 5; i++) {
printf("%d: %d\n", i, counts[i]);
}
return 0;
} |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #NewLISP | NewLISP | (lambda (s) (print (list s (list 'quote s)))) |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Vlang | Vlang | const max_tail = 256
struct Queue<T> {
mut:
data []T
tail int
head int
}
fn (mut queue Queue<T>) push(value T) {
if queue.tail >= max_tail || queue.tail < queue.head {
return
}
println('push: $value')
queue.data << value
queue.tail++
}
fn (mut queue Queue<T>) pop() !T {
if queue.tail > 0 && queue.head < queue.tail {
result := queue.data[queue.head]
queue.head++
println('Dequeue: top of Queue was $result')
return result
}
return error('Queue Underflow!!')
}
fn (queue Queue<T>) peek() !T {
if queue.tail > 0 && queue.head < queue.tail {
result := queue.data[queue.head]
println('Peek: top of Queue is $result')
return result
}
return error('Out of Bounds...')
}
fn (queue Queue<T>) empty() bool {
return queue.tail == 0
}
fn main() {
mut queue := Queue<f64>{}
println('Queue is empty? ' + if queue.empty() { 'Yes' } else { 'No' })
queue.push(5.0)
queue.push(4.2)
println('Queue is empty? ' + if queue.empty() { 'Yes' } else { 'No' })
queue.peek() or { return }
queue.pop() or { return }
queue.pop() or { return }
queue.push(1.2)
} |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Wart | Wart | def (queue seq)
(tag queue (list seq lastcons.seq len.seq))
def (enq x q)
do1 x
let (l last len) rep.q
rep.q.2 <- (len + 1)
if no.l
rep.q.1 <- (rep.q.0 <- list.x)
rep.q.1 <- (cdr.last <- list.x)
def (deq q)
let (l last len) rep.q
ret ans car.l
unless zero?.len
rep.q.2 <- (len - 1)
rep.q.0 <- cdr.l
def (len q) :case (isa queue q)
rep.q.2 |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #C.2B.2B | C++ | #include <array>
#include <cstdint>
#include <iostream>
class XorShiftStar {
private:
const uint64_t MAGIC = 0x2545F4914F6CDD1D;
uint64_t state;
public:
void seed(uint64_t num) {
state = num;
}
uint32_t next_int() {
uint64_t x;
uint32_t answer;
x = state;
x = x ^ (x >> 12);
x = x ^ (x << 25);
x = x ^ (x >> 27);
state = x;
answer = ((x * MAGIC) >> 32);
return answer;
}
float next_float() {
return (float)next_int() / (1LL << 32);
}
};
int main() {
auto rng = new XorShiftStar();
rng->seed(1234567);
std::cout << rng->next_int() << '\n';
std::cout << rng->next_int() << '\n';
std::cout << rng->next_int() << '\n';
std::cout << rng->next_int() << '\n';
std::cout << rng->next_int() << '\n';
std::cout << '\n';
std::array<int, 5> counts = { 0, 0, 0, 0, 0 };
rng->seed(987654321);
for (int i = 0; i < 100000; i++) {
int j = (int)floor(rng->next_float() * 5.0);
counts[j]++;
}
for (size_t i = 0; i < counts.size(); i++) {
std::cout << i << ": " << counts[i] << '\n';
}
return 0;
} |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Nim | Nim | |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Wren | Wren | import "/queue" for Queue
var q = Queue.new()
var item = q.pop()
if (item == null) {
System.print("ERROR: attempted to pop from an empty queue")
} else {
System.print("'%(item)' was popped")
} |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #D | D | import std.math;
import std.stdio;
class XorShiftStar {
private immutable MAGIC = 0x2545F4914F6CDD1D;
private ulong state;
public void seed(ulong num) {
state = num;
}
public uint nextInt() {
ulong x;
uint answer;
x = state;
x = x ^ (x >> 12);
x = x ^ (x << 25);
x = x ^ (x >> 27);
state = x;
answer = ((x * MAGIC) >> 32);
return answer;
}
public float nextFloat() {
return cast(float) nextInt() / (1L << 32);
}
}
void main() {
auto rng = new XorShiftStar();
rng.seed(1234567);
writeln(rng.nextInt);
writeln(rng.nextInt);
writeln(rng.nextInt);
writeln(rng.nextInt);
writeln(rng.nextInt);
writeln;
int[5] counts;
rng.seed(987654321);
foreach (_; 0 .. 100_000) {
auto j = cast(int) floor(rng.nextFloat * 5.0);
counts[j]++;
}
foreach (i, v; counts) {
writeln(i, ": ", v);
}
} |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #NS-HUBASIC | NS-HUBASIC | 10 LIST |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #XLISP | XLISP | (define-class queue
(instance-variables vals))
(define-method (queue 'initialize)
(setq vals '())
self)
(define-method (queue 'push x)
(setq vals (nconc vals (cons x nil))))
(define-method (queue 'pop)
(define val (car vals))
(setq vals (cdr vals))
val)
(define-method (queue 'emptyp)
(null vals)) |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #Delphi | Delphi |
program Xorshift_star;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
type
TXorshiftStar = record
private
state: uint64;
const
k = $2545F4914F6CDD1D;
public
constructor Create(aState: uint64);
procedure Seed(aState: uint64);
function NextInt: uint32;
function NextFloat: Extended;
end;
{ TXorshiftStar }
constructor TXorshiftStar.Create(aState: uint64);
begin
Seed(aState);
end;
function TXorshiftStar.NextFloat: Extended;
begin
Result := NextInt() / $100000000;
end;
function TXorshiftStar.NextInt: uint32;
var
x: UInt64;
begin
x := state;
x := x xor (x shr 12);
x := x xor (x shl 25);
x := x xor (x shr 27);
state := x;
Result := uint32((x * k) shr 32);
end;
procedure TXorshiftStar.Seed(aState: uint64);
begin
state := aState;
end;
begin
var randomGen := TXorshiftStar.Create(1234567);
for var i := 0 to 4 do
writeln(randomGen.NextInt);
var counts := [0, 0, 0, 0, 0];
randomGen.seed(987654321);
for var i := 1 to 100000 do
begin
var j := Floor(randomGen.nextFloat() * 5);
inc(counts[j]);
end;
writeln(#10'The counts for 100,000 repetitions are:');
for var i := 0 to 4 do
writeln(format(' %d : %d', [i, counts[i]]));
{$IFNDEF UNIX} Readln; {$ENDIF}
end. |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Oberon-2 | Oberon-2 | MODULE M;
IMPORT O:=Out;
CONST
T=";PROCEDURE c*;BEGIN O.Char(22X);O.String(T) END c;BEGIN O.String('MODULE M;IMPORT O:=Out;CONST T=');c END M.";
PROCEDURE c*;
BEGIN
O.Char(22X);O.String(T)
END c;
BEGIN
O.String('MODULE M;IMPORT O:=Out;CONST T=');
c
END M. |
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method | Pseudo-random numbers/Middle-square method | Middle-square_method Generator
The Method
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers.
Pseudo code
var seed = 675248
function random()
var s = str(seed * seed) 'str: turn a number into string
do while not len(s) = 12
s = "0" + s 'add zeroes before the string
end do
seed = val(mid(s, 4, 6)) 'mid: string variable, start, length
'val: turn a string into number
return seed
end function
Middle-square method use
for i = 1 to 5
print random()
end for
Task
Generate a class/set of functions that generates pseudo-random
numbers (6 digits) as shown above.
Show the first five integers generated with the seed 675248 as shown above.
Show your output here, on this page. | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program pRandom64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz " @ \n"
szCarriageReturn: .asciz "\n"
qSeed: .quad 675248
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrqSeed
ldr x3,[x0]
mov x2,#5
1:
mov x0,x3
bl computePseudo
mov x3,x0
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display message
subs x2,x2,#1
bgt 1b
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrsZoneConv: .quad sZoneConv
qAdrqSeed: .quad qSeed
/***************************************************/
/* compute pseudo random number */
/***************************************************/
/* x0 contains the number */
computePseudo:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0
mul x0,x2,x2
ldr x2,qdiv
udiv x1,x0,x2
ldr x2,qdiv2
udiv x0,x1,x2
msub x0,x2,x0,x1
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qdiv: .quad 1000
qdiv2: .quad 1000000
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #XPL0 | XPL0 | include c:\cxpl\codes;
def Size=8;
int Fifo(Size);
int In, Out; \fill and empty indexes into Fifo
proc Push(A); \Add integer A to queue
int A; \(overflow not detected)
[Fifo(In):= A;
In:= In+1;
if In >= Size then In:= 0;
];
func Pop; \Return first integer in queue
int A;
[if Out=In then \if popping empty queue
[Text(0, "Error"); exit 1]; \ then exit program with error code 1
A:= Fifo(Out);
Out:= Out+1;
if Out >= Size then Out:= 0;
return A;
];
func Empty; \Return 'true' if queue is empty
return In = Out;
[In:= 0; Out:= 0;
Push(0);
Text(0, if Empty then "true" else "false"); CrLf(0);
IntOut(0, Pop); CrLf(0);
Push(1);
Push(2);
Push(3);
IntOut(0, Pop); CrLf(0);
IntOut(0, Pop); CrLf(0);
IntOut(0, Pop); CrLf(0);
Text(0, if Empty then "true" else "false"); CrLf(0);
\A 256-byte queue is built in as device 8:
OpenI(8); OpenO(8);
ChOut(8, ^0); \push
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(8, ^1); \push
ChOut(8, ^2); \push
ChOut(8, ^3); \push
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
] |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #F.23 | F# |
// Xorshift star. Nigel Galloway: August 14th., 2020
let fN=(fun(n:uint64)->n^^^(n>>>12))>>(fun n->n^^^(n<<<25))>>(fun n->n^^^(n>>>27))
let Xstar32=Seq.unfold(fun n->let n=fN n in Some(uint32((n*0x2545F4914F6CDD1DUL)>>>32),n))
let XstarF n=Xstar32 n|>Seq.map(fun n->(float n)/4294967296.0)
|
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #Factor | Factor | USING: accessors kernel literals math math.statistics
prettyprint sequences ;
CONSTANT: mask64 $[ 1 64 shift 1 - ]
CONSTANT: mask32 $[ 1 32 shift 1 - ]
CONSTANT: const 0x2545F4914F6CDD1D
! Restrict seed value to positive integers.
PREDICATE: positive < integer 0 > ;
ERROR: seed-nonpositive seed ;
TUPLE: xorshift* { state positive initial: 1 } ;
: <xorshift*> ( seed -- xorshift* )
dup positive? [ seed-nonpositive ] unless
mask64 bitand xorshift* boa ;
: twiddle ( m n -- n ) dupd shift bitxor mask64 bitand ;
: next-int ( obj -- n )
dup state>> -12 twiddle 25 twiddle -27 twiddle tuck swap
state<< const * mask64 bitand -32 shift mask32 bitand ;
: next-float ( obj -- x ) next-int 1 32 shift /f ;
! ---=== Task ===---
1234567 <xorshift*> 5 [ dup next-int . ] times
987654321 >>state
100,000 [ dup next-float 5 * >integer ] replicate nip
histogram . |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Objeck | Objeck | class Program { function : Main(args : String[]) ~ Nil { s := "class Program { function : Main(args : String[]) ~ Nil { s :=; IO.Console->Print(s->SubString(61))->Print(34->As(Char))->Print(s)->Print(34->As(Char))->PrintLine(s->SubString(61, 129)); } }"; IO.Console->Print(s->SubString(61))->Print(34->As(Char))->Print(s)->Print(34->As(Char))->PrintLine(s->SubString(61, 129)); } } |
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method | Pseudo-random numbers/Middle-square method | Middle-square_method Generator
The Method
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers.
Pseudo code
var seed = 675248
function random()
var s = str(seed * seed) 'str: turn a number into string
do while not len(s) = 12
s = "0" + s 'add zeroes before the string
end do
seed = val(mid(s, 4, 6)) 'mid: string variable, start, length
'val: turn a string into number
return seed
end function
Middle-square method use
for i = 1 to 5
print random()
end for
Task
Generate a class/set of functions that generates pseudo-random
numbers (6 digits) as shown above.
Show the first five integers generated with the seed 675248 as shown above.
Show your output here, on this page. | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
type long is range 0 .. 2**64;
Seed : long := 675_248;
function random return long is
begin
Seed := Seed * Seed / 1_000 rem 1_000_000;
return Seed;
end random;
begin
for I in 1 .. 5 loop
Put (long'Image (random));
end loop;
New_Line;
end Main; |
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method | Pseudo-random numbers/Middle-square method | Middle-square_method Generator
The Method
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers.
Pseudo code
var seed = 675248
function random()
var s = str(seed * seed) 'str: turn a number into string
do while not len(s) = 12
s = "0" + s 'add zeroes before the string
end do
seed = val(mid(s, 4, 6)) 'mid: string variable, start, length
'val: turn a string into number
return seed
end function
Middle-square method use
for i = 1 to 5
print random()
end for
Task
Generate a class/set of functions that generates pseudo-random
numbers (6 digits) as shown above.
Show the first five integers generated with the seed 675248 as shown above.
Show your output here, on this page. | #ALGOL_68 | ALGOL 68 | BEGIN # generate random numbers by the middle-square method #
INT seed := 675248;
# returns the next middle-square random number #
PROC ms random = INT: seed := SHORTEN( ( ( LONG INT( seed ) * LONG INT( seed ) ) OVER 1000 ) MOD 1 000 000 );
# test the ms random procedure #
FOR i TO 5 DO
print( ( " ", whole( ms random, 0 ) ) )
OD
END |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #zkl | zkl | class Queue{
var [const] q=List();
fcn push { q.append(vm.pasteArgs()) }
fcn pop { q.pop(0) }
fcn empty { q.len()==0 }
} |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #Go | Go | package main
import (
"fmt"
"math"
)
const CONST = 0x2545F4914F6CDD1D
type XorshiftStar struct{ state uint64 }
func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }
func (xor *XorshiftStar) seed(state uint64) { xor.state = state }
func (xor *XorshiftStar) nextInt() uint32 {
x := xor.state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
xor.state = x
return uint32((x * CONST) >> 32)
}
func (xor *XorshiftStar) nextFloat() float64 {
return float64(xor.nextInt()) / (1 << 32)
}
func main() {
randomGen := XorshiftStarNew(1234567)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d : %d\n", i, counts[i])
}
} |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #OCaml | OCaml | (fun p -> Printf.printf p (string_of_format p)) "(fun p -> Printf.printf p (string_of_format p)) %S;;\n";; |
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32 | Pseudo-random numbers/PCG32 | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
| Bitwise or operator
https://en.wikipedia.org/wiki/Bitwise_operation#OR
Bitwise comparison gives 1 if any of corresponding bits are 1
E.g Binary 00110101 | Binary 00110011 == Binary 00110111
PCG32 Generator (pseudo-code)
PCG32 has two unsigned 64-bit integers of internal state:
state: All 2**64 values may be attained.
sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).
Values of sequence allow 2**63 different sequences of random numbers from the same state.
The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-
const N<-U64 6364136223846793005
const inc<-U64 (seed_sequence << 1) | 1
state<-U64 ((inc+seed_state)*N+inc
do forever
xs<-U32 (((state>>18)^state)>>27)
rot<-INT (state>>59)
OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))
state<-state*N+inc
end do
Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.
Task
Generate a class/set of functions that generates pseudo-random
numbers using the above.
Show that the first five integers generated with the seed 42, 54
are: 2707161783 2068313097 3122475824 2211639955 3215226955
Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005
Show your output here, on this page.
| #11l | 11l | T PCG32
UInt64 state, inc
F next_int()
V old = .state
.state = (old * 6364136223846793005) + .inc
V shifted = UInt32(((old >> 18) (+) old) >> 27)
V rot = UInt32(old >> 59)
R (shifted >> rot) [|] (shifted << (((-)rot + 1) [&] 31))
F seed(UInt64 seed_state, seed_sequence)
.state = 0
.inc = (seed_sequence << 1) [|] 1
.next_int()
.state += seed_state
.next_int()
F next_float()
R Float(.next_int()) / (UInt64(1) << 32)
V random_gen = PCG32()
random_gen.seed(42, 54)
L 5
print(random_gen.next_int())
random_gen.seed(987654321, 1)
V hist = Dict(0.<5, i -> (i, 0))
L 100'000
hist[Int(random_gen.next_float() * 5)]++
print(hist) |
http://rosettacode.org/wiki/Pythagorean_quadruples | Pythagorean quadruples |
One form of Pythagorean quadruples is (for positive integers a, b, c, and d):
a2 + b2 + c2 = d2
An example:
22 + 32 + 62 = 72
which is:
4 + 9 + 36 = 49
Task
For positive integers up 2,200 (inclusive), for all values of a,
b, c, and d,
find (and show here) those values of d that can't be represented.
Show the values of d on one line of output (optionally with a title).
Related tasks
Euler's sum of powers conjecture.
Pythagorean triples.
Reference
the Wikipedia article: Pythagorean quadruple.
| #11l | 11l | F quad(top = 2200)
V r = [0B] * top
V ab = [0B] * (top * 2)^2
L(a) 1 .< top
L(b) a .< top
ab[a * a + b * b] = 1B
V s = 3
L(c) 1 .< top
(V s1, s, V s2) = (s, s + 2, s + 2)
L(d) c + 1 .< top
I ab[s1]
r[d] = 1B
s1 += s2
s2 += 2
R enumerate(r).filter((i, val) -> !val & i).map((i, val) -> i)
print(quad()) |
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method | Pseudo-random numbers/Middle-square method | Middle-square_method Generator
The Method
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers.
Pseudo code
var seed = 675248
function random()
var s = str(seed * seed) 'str: turn a number into string
do while not len(s) = 12
s = "0" + s 'add zeroes before the string
end do
seed = val(mid(s, 4, 6)) 'mid: string variable, start, length
'val: turn a string into number
return seed
end function
Middle-square method use
for i = 1 to 5
print random()
end for
Task
Generate a class/set of functions that generates pseudo-random
numbers (6 digits) as shown above.
Show the first five integers generated with the seed 675248 as shown above.
Show your output here, on this page. | #AppleScript | AppleScript | on newGenerator(n, seed)
script generator
property seed : missing value
property p1 : 10 ^ (n div 2)
property p2 : 10 ^ n
on getRandom()
set seed to seed * seed div p1 mod p2
return seed div 1
end getRandom
end script
set generator's seed to seed mod (10 ^ n)
return generator
end newGenerator
local generator, output
set generator to newGenerator(6, 675248)
set output to {}
repeat 5 times
set end of output to generator's getRandom()
end repeat
return output |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #Haskell | Haskell | import Data.Bits
import Data.Word
import System.Random
import Data.List
newtype XorShift = XorShift Word64
instance RandomGen XorShift where
next (XorShift state) = (out newState, XorShift newState)
where
newState = (\z -> z `xor` (z `shiftR` 27)) .
(\z -> z `xor` (z `shiftL` 25)) .
(\z -> z `xor` (z `shiftR` 12)) $ state
out x = fromIntegral $ (x * 0x2545f4914f6cdd1d) `shiftR` 32
split _ = error "XorShift is not splittable"
randoms' :: RandomGen g => g -> [Int]
randoms' = unfoldr (pure . next)
toFloat n = fromIntegral n / (2^32 - 1) |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Oforth | Oforth | "dup 34 emit print 34 emit BL emit print" dup 34 emit print 34 emit BL emit print |
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32 | Pseudo-random numbers/PCG32 | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
| Bitwise or operator
https://en.wikipedia.org/wiki/Bitwise_operation#OR
Bitwise comparison gives 1 if any of corresponding bits are 1
E.g Binary 00110101 | Binary 00110011 == Binary 00110111
PCG32 Generator (pseudo-code)
PCG32 has two unsigned 64-bit integers of internal state:
state: All 2**64 values may be attained.
sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).
Values of sequence allow 2**63 different sequences of random numbers from the same state.
The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-
const N<-U64 6364136223846793005
const inc<-U64 (seed_sequence << 1) | 1
state<-U64 ((inc+seed_state)*N+inc
do forever
xs<-U32 (((state>>18)^state)>>27)
rot<-INT (state>>59)
OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))
state<-state*N+inc
end do
Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.
Task
Generate a class/set of functions that generates pseudo-random
numbers using the above.
Show that the first five integers generated with the seed 42, 54
are: 2707161783 2068313097 3122475824 2211639955 3215226955
Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005
Show your output here, on this page.
| #Ada | Ada | with Interfaces; use Interfaces;
package random_pcg32 is
function Next_Int return Unsigned_32;
function Next_Float return Long_Float;
procedure Seed (seed_state : Unsigned_64; seed_sequence : Unsigned_64);
end random_pcg32;
|
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32 | Pseudo-random numbers/PCG32 | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
| Bitwise or operator
https://en.wikipedia.org/wiki/Bitwise_operation#OR
Bitwise comparison gives 1 if any of corresponding bits are 1
E.g Binary 00110101 | Binary 00110011 == Binary 00110111
PCG32 Generator (pseudo-code)
PCG32 has two unsigned 64-bit integers of internal state:
state: All 2**64 values may be attained.
sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).
Values of sequence allow 2**63 different sequences of random numbers from the same state.
The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-
const N<-U64 6364136223846793005
const inc<-U64 (seed_sequence << 1) | 1
state<-U64 ((inc+seed_state)*N+inc
do forever
xs<-U32 (((state>>18)^state)>>27)
rot<-INT (state>>59)
OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))
state<-state*N+inc
end do
Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.
Task
Generate a class/set of functions that generates pseudo-random
numbers using the above.
Show that the first five integers generated with the seed 42, 54
are: 2707161783 2068313097 3122475824 2211639955 3215226955
Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005
Show your output here, on this page.
| #ALGOL_68 | ALGOL 68 | BEGIN # generate some pseudo random numbers using PCG32 #
# note that although LONG INT is 64 bits in Algol 68G, LONG BITS is longer than 64 bits #
LONG BITS state := LONG 16r853c49e6748fea9b;
LONG INT inc := ABS LONG 16rda3e39cb94b95bdb;
LONG BITS mask 64 = LONG 16rffffffffffffffff;
LONG BITS mask 32 = LONG 16rffffffff;
LONG BITS mask 31 = LONG 16r7fffffff;
LONG INT one shl 32 = ABS ( LONG 16r1 SHL 32 );
# XOR and assign convenience operator #
PRIO XORAB = 1;
OP XORAB = ( REF LONG BITS x, LONG BITS v )REF LONG BITS: x := ( x XOR v ) AND mask 64;
# initialises the state to the specified seed #
PROC seed = ( LONG INT seed state, seed sequence )VOID:
BEGIN
state := 16r0;
inc := ABS ( ( ( BIN seed sequence SHL 1 ) OR 16r1 ) AND mask 64 );
next int;
state := SHORTEN ( BIN ( ABS state + seed state ) AND mask 64 );
next int
END # seed # ;
# gets the next pseudo random integer #
PROC next int = LONG INT:
BEGIN
LONG BITS old = state;
LONG INT const = LONG 6364136223846793005;
state := SHORTEN ( mask 64 AND BIN ( ( ABS old * LENG const ) + inc ) );
LONG BITS x := old;
x XORAB ( old SHR 18 );
BITS xor shifted = SHORTEN ( mask 32 AND ( x SHR 27 ) );
INT rot = SHORTEN ABS ( mask 32 AND ( old SHR 59 ) );
INT rot 2 = IF rot = 0 THEN 0 ELSE 32 - rot FI;
BITS xor shr := SHORTEN ( mask 32 AND LENG ( xor shifted SHR rot ) );
BITS xor shl := xor shifted;
TO rot 2 DO
xor shl := SHORTEN ( ( mask 31 AND LENG xor shl ) SHL 1 )
OD;
ABS ( LENG xor shr OR LENG xor shl )
END # next int # ;
# gets the next pseudo random real #
PROC next float = LONG REAL: next int / one shl 32;
BEGIN # task test cases #
seed( 42, 54 );
print( ( whole( next int, 0 ), newline ) ); # 2707161783 #
print( ( whole( next int, 0 ), newline ) ); # 2068313097 #
print( ( whole( next int, 0 ), newline ) ); # 3122475824 #
print( ( whole( next int, 0 ), newline ) ); # 2211639955 #
print( ( whole( next int, 0 ), newline ) ); # 3215226955 #
# count the number of occurances of 0..4 in a sequence of pseudo random reals scaled to be in [0..5) #
seed( 987654321, 1 );
[ 0 : 4 ]INT counts; FOR i FROM LWB counts TO UPB counts DO counts[ i ] := 0 OD;
TO 100 000 DO counts[ SHORTEN ENTIER ( next float * 5 ) ] +:= 1 OD;
FOR i FROM LWB counts TO UPB counts DO
print( ( whole( i, -2 ), ": ", whole( counts[ i ], -6 ) ) )
OD;
print( ( newline ) )
END
END |
http://rosettacode.org/wiki/Pythagorean_quadruples | Pythagorean quadruples |
One form of Pythagorean quadruples is (for positive integers a, b, c, and d):
a2 + b2 + c2 = d2
An example:
22 + 32 + 62 = 72
which is:
4 + 9 + 36 = 49
Task
For positive integers up 2,200 (inclusive), for all values of a,
b, c, and d,
find (and show here) those values of d that can't be represented.
Show the values of d on one line of output (optionally with a title).
Related tasks
Euler's sum of powers conjecture.
Pythagorean triples.
Reference
the Wikipedia article: Pythagorean quadruple.
| #ALGOL_68 | ALGOL 68 | BEGIN
# find values of d where d^2 =/= a^2 + b^2 + c^2 for any integers a, b, c #
# where d in [1..2200], a, b, c =/= 0 #
# max number to check #
INT max number = 2200;
INT max square = max number * max number;
# table of numbers that can be the sum of two squares #
[ 1 : max square ]BOOL sum of two squares; FOR n TO max square DO sum of two squares[ n ] := FALSE OD;
FOR a TO max number DO
INT a2 = a * a;
FOR b FROM a TO max number WHILE INT sum2 = ( b * b ) + a2;
sum2 <= max square DO
sum of two squares[ sum2 ] := TRUE
OD
OD;
# now find d such that d^2 - c^2 is in sum of two squares #
[ 1 : max number ]BOOL solution; FOR n TO max number DO solution[ n ] := FALSE OD;
FOR d TO max number DO
INT d2 = d * d;
FOR c TO d - 1 WHILE NOT solution[ d ] DO
INT diff2 = d2 - ( c * c );
IF sum of two squares[ diff2 ] THEN
solution[ d ] := TRUE
FI
OD
OD;
# print the numbers whose squares are not the sum of three squares #
FOR d TO max number DO
IF NOT solution[ d ] THEN
print( ( " ", whole( d, 0 ) ) )
FI
OD;
print( ( newline ) )
END |
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method | Pseudo-random numbers/Middle-square method | Middle-square_method Generator
The Method
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers.
Pseudo code
var seed = 675248
function random()
var s = str(seed * seed) 'str: turn a number into string
do while not len(s) = 12
s = "0" + s 'add zeroes before the string
end do
seed = val(mid(s, 4, 6)) 'mid: string variable, start, length
'val: turn a string into number
return seed
end function
Middle-square method use
for i = 1 to 5
print random()
end for
Task
Generate a class/set of functions that generates pseudo-random
numbers (6 digits) as shown above.
Show the first five integers generated with the seed 675248 as shown above.
Show your output here, on this page. | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android with termux */
/* program pRandom.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz " @ \n"
szCarriageReturn: .asciz "\n"
iSeed: .int 675248
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdriSeed
ldr r3,[r0]
mov r2,#5
1:
mov r0,r3
bl computePseudo
mov r3,r0
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display message
subs r2,r2,#1
bgt 1b
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrsZoneConv: .int sZoneConv
iAdriSeed: .int iSeed
/***************************************************/
/* compute pseudo random number */
/***************************************************/
/* r0 contains the number */
computePseudo:
push {r1-r2,lr} @ save registers
mov r2,r0
umull r0,r1,r2,r2
ldr r2,idiv
bl division32R
ldr r2,idiv2
bl division32R
mov r0,r2
pop {r1-r2,pc} @ restaur registers
idiv: .int 1000
idiv2: .int 1000000
/***************************************************/
/* division number 64 bits in 2 registers by number 32 bits */
/***************************************************/
/* r0 contains lower part dividende */
/* r1 contains upper part dividende */
/* r2 contains divisor */
/* r0 return lower part quotient */
/* r1 return upper part quotient */
/* r2 return remainder */
division32R:
push {r3-r9,lr} @ save registers
mov r6,#0 @ init upper upper part remainder !!
mov r7,r1 @ init upper part remainder with upper part dividende
mov r8,r0 @ init lower part remainder with lower part dividende
mov r9,#0 @ upper part quotient
mov r4,#0 @ lower part quotient
mov r5,#32 @ bits number
1: @ begin loop
lsl r6,#1 @ shift upper upper part remainder
lsls r7,#1 @ shift upper part remainder
orrcs r6,#1
lsls r8,#1 @ shift lower part remainder
orrcs r7,#1
lsls r4,#1 @ shift lower part quotient
lsl r9,#1 @ shift upper part quotient
orrcs r9,#1
@ divisor sustract upper part remainder
subs r7,r2
sbcs r6,#0 @ and substract carry
bmi 2f @ négative ?
@ positive or equal
orr r4,#1 @ 1 -> right bit quotient
b 3f
2: @ negative
orr r4,#0 @ 0 -> right bit quotient
adds r7,r2 @ and restaur remainder
adc r6,#0
3:
subs r5,#1 @ decrement bit size
bgt 1b @ end ?
mov r0,r4 @ lower part quotient
mov r1,r9 @ upper part quotient
mov r2,r7 @ remainder
100: @ function end
pop {r3-r9,lr} @ restaur registers
bx lr
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #Java | Java | public class XorShiftStar {
private static final long MAGIC = Long.parseUnsignedLong("2545F4914F6CDD1D", 16);
private long state;
public void seed(long num) {
state = num;
}
public int nextInt() {
long x;
int answer;
x = state;
x = x ^ (x >>> 12);
x = x ^ (x << 25);
x = x ^ (x >>> 27);
state = x;
answer = (int) ((x * MAGIC) >> 32);
return answer;
}
public float nextFloat() {
return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);
}
public static void main(String[] args) {
var rng = new XorShiftStar();
rng.seed(1234567);
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println();
int[] counts = {0, 0, 0, 0, 0};
rng.seed(987654321);
for (int i = 0; i < 100_000; i++) {
int j = (int) Math.floor(rng.nextFloat() * 5.0);
counts[j]++;
}
for (int i = 0; i < counts.length; i++) {
System.out.printf("%d: %d\n", i, counts[i]);
}
}
} |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #Ol | Ol | ((lambda (s) (display (list s (list (quote quote) s)))) (quote (lambda (s) (display (list s (list (quote quote) s)))))) |
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32 | Pseudo-random numbers/PCG32 | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
| Bitwise or operator
https://en.wikipedia.org/wiki/Bitwise_operation#OR
Bitwise comparison gives 1 if any of corresponding bits are 1
E.g Binary 00110101 | Binary 00110011 == Binary 00110111
PCG32 Generator (pseudo-code)
PCG32 has two unsigned 64-bit integers of internal state:
state: All 2**64 values may be attained.
sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).
Values of sequence allow 2**63 different sequences of random numbers from the same state.
The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-
const N<-U64 6364136223846793005
const inc<-U64 (seed_sequence << 1) | 1
state<-U64 ((inc+seed_state)*N+inc
do forever
xs<-U32 (((state>>18)^state)>>27)
rot<-INT (state>>59)
OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))
state<-state*N+inc
end do
Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.
Task
Generate a class/set of functions that generates pseudo-random
numbers using the above.
Show that the first five integers generated with the seed 42, 54
are: 2707161783 2068313097 3122475824 2211639955 3215226955
Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005
Show your output here, on this page.
| #C | C | #include <math.h>
#include <stdint.h>
#include <stdio.h>
const uint64_t N = 6364136223846793005;
static uint64_t state = 0x853c49e6748fea9b;
static uint64_t inc = 0xda3e39cb94b95bdb;
uint32_t pcg32_int() {
uint64_t old = state;
state = old * N + inc;
uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
uint32_t rot = old >> 59;
return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
}
double pcg32_float() {
return ((double)pcg32_int()) / (1LL << 32);
}
void pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {
state = 0;
inc = (seed_sequence << 1) | 1;
pcg32_int();
state = state + seed_state;
pcg32_int();
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
pcg32_seed(42, 54);
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("\n");
pcg32_seed(987654321, 1);
for (i = 0; i < 100000; i++) {
int j = (int)floor(pcg32_float() * 5.0);
counts[j]++;
}
printf("The counts for 100,000 repetitions are:\n");
for (i = 0; i < 5; i++) {
printf(" %d : %d\n", i, counts[i]);
}
return 0;
} |
http://rosettacode.org/wiki/Pythagorean_quadruples | Pythagorean quadruples |
One form of Pythagorean quadruples is (for positive integers a, b, c, and d):
a2 + b2 + c2 = d2
An example:
22 + 32 + 62 = 72
which is:
4 + 9 + 36 = 49
Task
For positive integers up 2,200 (inclusive), for all values of a,
b, c, and d,
find (and show here) those values of d that can't be represented.
Show the values of d on one line of output (optionally with a title).
Related tasks
Euler's sum of powers conjecture.
Pythagorean triples.
Reference
the Wikipedia article: Pythagorean quadruple.
| #Amazing_Hopper | Amazing Hopper |
#include <flow.h>
DEF-MAIN(argv, argc)
SET(N, 2200)
DIM( MUL(MUL(N,N),2) ) AS-ZEROS( temp )
DIM( N ) AS-ZEROS( found )
MSET( a,T1,T2 )
TIC(T1)
SEQ-SPC(1,N,N,a), LET( a := MUL(a,a) )
SET(i,1), SET(r,0)
PERF-UP(i,N,1)
LET( r := ADD( [i] GET( a ), [i:end] CGET(a) ) )
SET-RANGE( r ), SET(temp, 1), CLR-RANGE
NEXT
SET(c,1), SET(s,3), MSET(s1,s2,d)
PERF-UP(c, N, 1)
LET( s1 := s )
s += 2
LET( s2 := s )
LET( d := ADD(c,1) )
PERF-UP(d, N, 1)
COND ( [s1] GET(temp) )
[d] {1} PUT(found)
CEND
s1 += s2
s2 += 2
NEXT
NEXT
TOC(T1, T2), PRNL("Time = ", T2 )
PRN( "Imprimiendo resultados:\n" )
CART( IS-ZERO?( found ) ) MOVE-TO( r )
PRNL( r )
MCLEAR(temp, found, a, r)
END
|
http://rosettacode.org/wiki/Pythagorean_quadruples | Pythagorean quadruples |
One form of Pythagorean quadruples is (for positive integers a, b, c, and d):
a2 + b2 + c2 = d2
An example:
22 + 32 + 62 = 72
which is:
4 + 9 + 36 = 49
Task
For positive integers up 2,200 (inclusive), for all values of a,
b, c, and d,
find (and show here) those values of d that can't be represented.
Show the values of d on one line of output (optionally with a title).
Related tasks
Euler's sum of powers conjecture.
Pythagorean triples.
Reference
the Wikipedia article: Pythagorean quadruple.
| #AppleScript | AppleScript | -- double :: Num -> Num
on double(x)
x + x
end double
-- powersOfTwo :: Generator [Int]
on powersOfTwo()
iterate(double, 1)
end powersOfTwo
on run
-- Two infinite lists, from each of which we can draw an arbitrary number of initial terms
set xs to powersOfTwo() -- {1, 2, 4, 8, 16, 32 ...
set ys to fmapGen(timesFive, powersOfTwo()) -- {5, 10, 20, 40, 80, 160 ...
-- Another infinite list, derived from the first two (sorted in rising value)
set zs to mergeInOrder(xs, ys) -- {1, 2, 4, 5, 8, 10 ...
-- Taking terms from the derived list while their value is below 2200 ...
takeWhileGen(le2200, zs)
--> {1, 2, 4, 5, 8, 10, 16, 20, 32, 40, 64, 80, 128, 160, 256, 320, 512, 640, 1024, 1280, 2048}
end run
-- le2200 :: Num -> Bool
on le2200(x)
x ≤ 2200
end le2200
-- timesFive :: Num -> Num
on timesFive(x)
5 * x
end timesFive
-- mergeInOrder :: Generator [Int] -> Generator [Int] -> Generator [Int]
on mergeInOrder(ga, gb)
script
property a : uncons(ga)
property b : uncons(gb)
on |λ|()
if (Nothing of a or Nothing of b) then
missing value
else
set ta to Just of a
set tb to Just of b
if |1| of ta < |1| of tb then
set a to uncons(|2| of ta)
return |1| of ta
else
set b to uncons(|2| of tb)
return |1| of tb
end if
end if
end |λ|
end script
end mergeInOrder
-- GENERIC -----------------------------------------------------------------
-- fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
on fmapGen(f, gen)
script
property g : gen
property mf : mReturn(f)'s |λ|
on |λ|()
set v to g's |λ|()
if v is missing value then
v
else
mf(v)
end if
end |λ|
end script
end fmapGen
-- iterate :: (a -> a) -> a -> Gen [a]
on iterate(f, x)
script
property v : missing value
property g : mReturn(f)'s |λ|
on |λ|()
if missing value is v then
set v to x
else
set v to g(v)
end if
return v
end |λ|
end script
end iterate
-- Just :: a -> Maybe a
on Just(x)
{type:"Maybe", Nothing:false, Just:x}
end Just
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Nothing :: Maybe a
on Nothing()
{type:"Maybe", Nothing:true}
end Nothing
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to xs's |λ|()
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- takeWhileGen :: (a -> Bool) -> Gen [a] -> [a]
on takeWhileGen(p, xs)
set ys to {}
set v to |λ|() of xs
tell mReturn(p)
repeat while (|λ|(v))
set end of ys to v
set v to xs's |λ|()
end repeat
end tell
return ys
end takeWhileGen
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- uncons :: [a] -> Maybe (a, [a])
on uncons(xs)
set lng to |length|(xs)
if 0 = lng then
Nothing()
else
if (2 ^ 29 - 1) as integer > lng then
if class of xs is string then
set cs to text items of xs
Just(Tuple(item 1 of cs, rest of cs))
else
Just(Tuple(item 1 of xs, rest of xs))
end if
else
Just(Tuple(item 1 of take(1, xs), xs))
end if
end if
end uncons |
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method | Pseudo-random numbers/Middle-square method | Middle-square_method Generator
The Method
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers.
Pseudo code
var seed = 675248
function random()
var s = str(seed * seed) 'str: turn a number into string
do while not len(s) = 12
s = "0" + s 'add zeroes before the string
end do
seed = val(mid(s, 4, 6)) 'mid: string variable, start, length
'val: turn a string into number
return seed
end function
Middle-square method use
for i = 1 to 5
print random()
end for
Task
Generate a class/set of functions that generates pseudo-random
numbers (6 digits) as shown above.
Show the first five integers generated with the seed 675248 as shown above.
Show your output here, on this page. | #AWK | AWK |
# syntax: GAWK -f PSEUDO-RANDOM_NUMBERS_MIDDLE-SQUARE_METHOD.AWK
BEGIN {
seed = 675248
srand(seed)
for (i=1; i<=5; i++) {
printf("%2d: %s\n",i,main())
}
exit(0)
}
function main( s) {
s = seed ^ 2
while (length(s) < 12) {
s = "0" s
}
seed = substr(s,4,6)
return(seed)
}
|
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method | Pseudo-random numbers/Middle-square method | Middle-square_method Generator
The Method
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers.
Pseudo code
var seed = 675248
function random()
var s = str(seed * seed) 'str: turn a number into string
do while not len(s) = 12
s = "0" + s 'add zeroes before the string
end do
seed = val(mid(s, 4, 6)) 'mid: string variable, start, length
'val: turn a string into number
return seed
end function
Middle-square method use
for i = 1 to 5
print random()
end for
Task
Generate a class/set of functions that generates pseudo-random
numbers (6 digits) as shown above.
Show the first five integers generated with the seed 675248 as shown above.
Show your output here, on this page. | #C | C | #include<stdio.h>
long long seed;
long long random(){
seed = seed * seed / 1000 % 1000000;
return seed;
}
int main(){
seed = 675248;
for(int i=1;i<=5;i++)
printf("%lld\n",random());
return 0;
} |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #Julia | Julia | const mask32 = (0x1 << 32) - 1
const CONST = 0x2545F4914F6CDD1D
mutable struct XorShiftStar
state::UInt64
end
XorShiftStar(_seed=0x0) = XorShiftStar(UInt(_seed))
seed(x::XorShiftStar, num) = begin x.state = UInt64(num) end
"""return random int between 0 and 2**32"""
function next_int(x::XorShiftStar)
x.state = x.state ⊻ (x.state >> 12)
x.state = x.state ⊻ (x.state << 25)
x.state = x.state ⊻ (x.state >> 27)
return ((x.state * CONST) >> 32) & mask32
end
"""return random float between 0 and 1"""
next_float(x::XorShiftStar) = next_int(x) / (1 << 32)
function testXorShiftStar()
random_gen = XorShiftStar()
seed(random_gen, 1234567)
for i in 1:5
println(next_int(random_gen))
end
seed(random_gen, 987654321)
hist = fill(0, 5)
for _ in 1:100_000
hist[Int(floor(next_float(random_gen) * 5)) + 1] += 1
end
foreach(n -> print(n - 1, ": ", hist[n], " "), 1:5)
end
testXorShiftStar()
|
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
Xorshift_star Generator (pseudo-code)
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
Xorshift use
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
Task
Generate a class/set of functions that generates pseudo-random
numbers as shown above.
Show that the first five integers genrated with the seed 1234567
are as shown above
Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
Show your output here, on this page.
| #Kotlin | Kotlin | import kotlin.math.floor
class XorShiftStar {
private var state = 0L
fun seed(num: Long) {
state = num
}
fun nextInt(): Int {
var x = state
x = x xor (x ushr 12)
x = x xor (x shl 25)
x = x xor (x ushr 27)
state = x
return (x * MAGIC shr 32).toInt()
}
fun nextFloat(): Float {
return nextInt().toUInt().toFloat() / (1L shl 32)
}
companion object {
private const val MAGIC = 0x2545F4914F6CDD1D
}
}
fun main() {
val rng = XorShiftStar()
rng.seed(1234567)
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println()
rng.seed(987654321)
val counts = arrayOf(0, 0, 0, 0, 0)
for (i in 1..100000) {
val j = floor(rng.nextFloat() * 5.0).toInt()
counts[j]++
}
for (iv in counts.withIndex()) {
println("${iv.index}: ${iv.value}")
}
} |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
| #ooRexx | ooRexx | say sourceline(1) |
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32 | Pseudo-random numbers/PCG32 | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
Examples are shown for 8 bit binary numbers; most significant bit to the left.
<< Logical shift left by given number of bits.
E.g Binary 00110101 << 2 == Binary 11010100
>> Logical shift right by given number of bits.
E.g Binary 00110101 >> 2 == Binary 00001101
^ Bitwise exclusive-or operator
https://en.wikipedia.org/wiki/Exclusive_or
Bitwise comparison for if bits differ
E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110
| Bitwise or operator
https://en.wikipedia.org/wiki/Bitwise_operation#OR
Bitwise comparison gives 1 if any of corresponding bits are 1
E.g Binary 00110101 | Binary 00110011 == Binary 00110111
PCG32 Generator (pseudo-code)
PCG32 has two unsigned 64-bit integers of internal state:
state: All 2**64 values may be attained.
sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).
Values of sequence allow 2**63 different sequences of random numbers from the same state.
The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-
const N<-U64 6364136223846793005
const inc<-U64 (seed_sequence << 1) | 1
state<-U64 ((inc+seed_state)*N+inc
do forever
xs<-U32 (((state>>18)^state)>>27)
rot<-INT (state>>59)
OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))
state<-state*N+inc
end do
Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.
Task
Generate a class/set of functions that generates pseudo-random
numbers using the above.
Show that the first five integers generated with the seed 42, 54
are: 2707161783 2068313097 3122475824 2211639955 3215226955
Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005
Show your output here, on this page.
| #C.2B.2B | C++ | #include <array>
#include <iostream>
class PCG32 {
private:
const uint64_t N = 6364136223846793005;
uint64_t state = 0x853c49e6748fea9b;
uint64_t inc = 0xda3e39cb94b95bdb;
public:
uint32_t nextInt() {
uint64_t old = state;
state = old * N + inc;
uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
uint32_t rot = old >> 59;
return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
}
double nextFloat() {
return ((double)nextInt()) / (1LL << 32);
}
void seed(uint64_t seed_state, uint64_t seed_sequence) {
state = 0;
inc = (seed_sequence << 1) | 1;
nextInt();
state = state + seed_state;
nextInt();
}
};
int main() {
auto r = new PCG32();
r->seed(42, 54);
std::cout << r->nextInt() << '\n';
std::cout << r->nextInt() << '\n';
std::cout << r->nextInt() << '\n';
std::cout << r->nextInt() << '\n';
std::cout << r->nextInt() << '\n';
std::cout << '\n';
std::array<int, 5> counts{ 0, 0, 0, 0, 0 };
r->seed(987654321, 1);
for (size_t i = 0; i < 100000; i++) {
int j = (int)floor(r->nextFloat() * 5.0);
counts[j]++;
}
std::cout << "The counts for 100,000 repetitions are:\n";
for (size_t i = 0; i < counts.size(); i++) {
std::cout << " " << i << " : " << counts[i] << '\n';
}
return 0;
} |
http://rosettacode.org/wiki/Pythagorean_quadruples | Pythagorean quadruples |
One form of Pythagorean quadruples is (for positive integers a, b, c, and d):
a2 + b2 + c2 = d2
An example:
22 + 32 + 62 = 72
which is:
4 + 9 + 36 = 49
Task
For positive integers up 2,200 (inclusive), for all values of a,
b, c, and d,
find (and show here) those values of d that can't be represented.
Show the values of d on one line of output (optionally with a title).
Related tasks
Euler's sum of powers conjecture.
Pythagorean triples.
Reference
the Wikipedia article: Pythagorean quadruple.
| #AWK | AWK |
# syntax: GAWK -f PYTHAGOREAN_QUADRUPLES.AWK
# converted from Go
BEGIN {
n = 2200
s = 3
for (a=1; a<=n; a++) {
a2 = a * a
for (b=a; b<=n; b++) {
ab[a2 + b * b] = 1
}
}
for (c=1; c<=n; c++) {
s1 = s
s += 2
s2 = s
for (d=c+1; d<=n; d++) {
if (ab[s1]) {
r[d] = 1
}
s1 += s2
s2 += 2
}
}
for (d=1; d<=n; d++) {
if (!r[d]) {
printf("%d ",d)
}
}
printf("\n")
exit(0)
}
|
http://rosettacode.org/wiki/Pythagoras_tree | Pythagoras tree |
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem.
Task
Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).
Related tasks
Fractal tree
| #Ada | Ada | with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Video.Rectangles;
with SDL.Events.Events;
procedure Pythagoras_Tree is
Width : constant := 600;
Height : constant := 600;
Level : constant := 7;
type Point is record X, Y : Float; end record;
B1 : constant Point := (X => 250.0, Y => 550.0);
B2 : constant Point := (X => 350.0, Y => 550.0);
Window : SDL.Video.Windows.Window;
Renderer : SDL.Video.Renderers.Renderer;
Event : SDL.Events.Events.Events;
procedure Draw_Pythagoras_Tree (Level : in Natural;
P1, P2 : in Point)
is
use SDL.Video.Rectangles;
Dx : constant Float := P2.X - P1.X;
Dy : constant Float := P1.Y - P2.Y;
R : constant Point := (X => P2.X - Dy, Y => P2.Y - Dx);
L : constant Point := (X => P1.X - Dy, Y => P1.Y - Dx);
M : constant Point := (X => L.X + (Dx - Dy) / 2.0,
Y => L.Y - (Dx + Dy) / 2.0);
CP1 : constant SDL.Video.Rectangles.Point := (C.int (P1.X), C.int (P1.Y));
CP2 : constant SDL.Video.Rectangles.Point := (C.int (P2.X), C.int (P2.Y));
CL : constant SDL.Video.Rectangles.Point := (C.int (L.X), C.int (L.Y));
CR : constant SDL.Video.Rectangles.Point := (C.int (R.X), C.int (R.Y));
CM : constant SDL.Video.Rectangles.Point := (C.int (M.X), C.int (M.Y));
Square : constant SDL.Video.Rectangles.Line_Arrays :=
((CP1, CP2), (CP2, CR), (CR, CL), (CL, CP1));
Triang : constant SDL.Video.Rectangles.Line_Arrays :=
((CR, CL), (CL, CM), (CM, CR));
begin
if Level > 0 then
Renderer.Set_Draw_Colour (Colour => (0, 220, 0, 255));
Renderer.Draw (Lines => Square);
Renderer.Draw (Lines => Triang);
Draw_Pythagoras_Tree (Level - 1, L, M);
Draw_Pythagoras_Tree (Level - 1, M, R);
end if;
end Draw_Pythagoras_Tree;
procedure Wait is
use type SDL.Events.Event_Types;
begin
loop
while SDL.Events.Events.Poll (Event) loop
if Event.Common.Event_Type = SDL.Events.Quit then
return;
end if;
end loop;
delay 0.100;
end loop;
end Wait;
begin
if not SDL.Initialise (Flags => SDL.Enable_Screen) then
return;
end if;
SDL.Video.Windows.Makers.Create (Win => Window,
Title => "Pythagoras tree",
Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
Size => SDL.Positive_Sizes'(Width, Height),
Flags => 0);
SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
Renderer.Set_Draw_Colour ((0, 0, 0, 255));
Renderer.Fill (Rectangle => (0, 0, Width, Height));
Renderer.Set_Draw_Colour ((0, 220, 0, 255));
Draw_Pythagoras_Tree (Level, B1, B2);
Window.Update_Surface;
Wait;
Window.Finalize;
SDL.Finalise;
end Pythagoras_Tree; |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.