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/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Go | Go | package main
import "fmt"
/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
typedef unsigned char byte;
typedef byte (*mcfunc) (byte, byte);
void runMachineCode(void *buf, byte a, byte b) {
mcfunc fp = (mcfunc)buf;
printf("%d\n", fp(a, b));
}
*/
import "C"
func main() {
code := []byte{
0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,
0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,
0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,
0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,
}
le := len(code)
buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC,
C.MAP_PRIVATE|C.MAP_ANON, -1, 0)
codePtr := C.CBytes(code)
C.memcpy(buf, codePtr, C.size_t(le))
var a, b byte = 7, 12
fmt.Printf("%d + %d = ", a, b)
C.runMachineCode(buf, C.byte(a), C.byte(b))
C.munmap(buf, C.size_t(le))
C.free(codePtr)
} |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Python | Python | # Python 3.0+ and 2.5+
try:
from functools import reduce
except:
pass
def mandelbrot(a):
return reduce(lambda z, _: z * z + a, range(50), 0)
def step(start, step, iterations):
return (start + (i * step) for i in range(iterations))
rows = (("*" if abs(mandelbrot(complex(x, y))) < 2 else " "
for x in step(-2.0, .0315, 80))
for y in step(1, -.05, 41))
print("\n".join("".join(row) for row in rows))
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Stata | Stata | . mat a=1,2,3\4,5,6
. mat b=1,1,0,0\1,0,0,1\0,0,1,1
. mat c=a*b
. mat list c
c[2,4]
c1 c2 c3 c4
r1 3 1 3 5
r2 9 4 6 11 |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Ursala | Ursala | #cast %eLL
example =
~&K7 <
<1.,2.,3.,4.>,
<5.,6.,7.,8.>,
<9.,10.,11.,12.>> |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #VBA | VBA | Function transpose(m As Variant) As Variant
transpose = WorksheetFunction.transpose(m)
End Function |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #Raku | Raku | use HTTP::UserAgent;
my $ua = HTTP::UserAgent.new;
$ua.timeout = 10; # seconds
my $server = 'http://api.macvendors.com/';
sub lookup ($mac) {
my $response = $ua.get: "$server+$mac";
sleep 1;
return $response.is-success ?? $response.content !! 'N/A';
CATCH { # Normally you would report some information about what
default { Nil } # went wrong, but the task specifies to ignore errors.
}
}
for <
BC:5F:F4
FC-A1-3E
10:dd:b1
00:0d:4b
23:45:67
> -> $mac { say lookup $mac } |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #Red | Red | print read rejoin [http://api.macvendors.com/ ask "MAC address: "]
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #BASIC | BASIC | dim answer$(20)
answer$[0] = "It is certain."
answer$[1] = "It is decidedly so."
answer$[2] = "Without a doubt."
answer$[3] = "Yes - definitely."
answer$[4] = "You may rely on it."
answer$[5] = "As I see it, yes."
answer$[6] = "Most likely."
answer$[7] = "Outlook good."
answer$[8] = "Yes."
answer$[9] = "Signs point to yes."
answer$[10] = "Reply hazy, try again."
answer$[11] = "Ask again later."
answer$[12] = "Better not tell you now."
answer$[13] = "Cannot predict now."
answer$[14] = "Concentrate and ask again."
answer$[15] = "Don't count on it."
answer$[16] = "My reply is no."
answer$[17] = "My sources say no."
answer$[18] = "Outlook not so good."
answer$[19] = "Very doubtful."
print "Q to quit."
while True
input string "What would you like to know? ", question$
if upper(question$) = "Q" then exit while
print answer$[int(rand * answer$[?])]
print
end while
end |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char *question = NULL;
size_t len = 0;
ssize_t read;
const char* answers[20] = {
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"
};
srand(time(NULL));
printf("Please enter your question or a blank line to quit.\n");
while (1) {
printf("\n? : ");
read = getline(&question, &len, stdin);
if (read < 2) break;
printf("\n%s\n", answers[rand() % 20]);
}
if (question) free(question);
return 0;
} |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Julia | Julia | using Cxx
cxx"""
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
int test (int a, int b)
{
/*
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
*/
char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};
void *buf;
int c;
/* copy code to executable buffer */
buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANON,-1,0);
memcpy (buf, code, sizeof(code));
/* run code */
c = ((int (*) (int, int))buf)(a, b);
/* free buffer */
munmap (buf, sizeof(code));
return c;
}
int main ()
{
printf("%d\n", test(7,12));
return 0;
}
"""
julia_function = @cxx main()
julia_function()
|
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Kotlin | Kotlin | // mcode.def
---
static inline unsigned char runMachineCode(void *code, unsigned char a, unsigned char b) {
return ((unsigned char (*) (unsigned char, unsigned char))code)(a, b);
} |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #R | R | iterate.until.escape <- function(z, c, trans, cond, max=50, response=dwell) {
#we iterate all active points in the same array operation,
#and keeping track of which points are still iterating.
active <- seq_along(z)
dwell <- z
dwell[] <- 0
for (i in 1:max) {
z[active] <- trans(z[active], c[active]);
survived <- cond(z[active])
dwell[active[!survived]] <- i
active <- active[survived]
if (length(active) == 0) break
}
eval(substitute(response))
}
re = seq(-2, 1, len=500)
im = seq(-1.5, 1.5, len=500)
c <- outer(re, im, function(x,y) complex(real=x, imaginary=y))
x <- iterate.until.escape(array(0, dim(c)), c,
function(z,c)z^2+c, function(z)abs(z) <= 2,
max=100)
image(x) |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Swift | Swift | @inlinable
public func matrixMult<T: Numeric>(_ m1: [[T]], _ m2: [[T]]) -> [[T]] {
let n = m1[0].count
let m = m1.count
let p = m2[0].count
guard m != 0 else {
return []
}
precondition(n == m2.count)
var ret = Array(repeating: Array(repeating: T.zero, count: p), count: m)
for i in 0..<m {
for j in 0..<p {
for k in 0..<n {
ret[i][j] += m1[i][k] * m2[k][j]
}
}
}
return ret
}
@inlinable
public func printMatrix<T>(_ matrix: [[T]]) {
guard !matrix.isEmpty else {
print()
return
}
let rows = matrix.count
let cols = matrix[0].count
for i in 0..<rows {
for j in 0..<cols {
print(matrix[i][j], terminator: " ")
}
print()
}
}
let m1 = [
[6.5, 2, 3],
[4.5, 1, 5]
]
let m2 = [
[10.0, 16, 23, 50],
[12, -8, 16, -4],
[70, 60, -1, -2]
]
let m3 = matrixMult(m1, m2)
printMatrix(m3) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #VBScript | VBScript |
'create and display the initial matrix
WScript.StdOut.WriteLine "Initial Matrix:"
x = 4 : y = 6 : n = 1
Dim matrix()
ReDim matrix(x,y)
For i = 0 To y
For j = 0 To x
matrix(j,i) = n
If j < x Then
WScript.StdOut.Write n & vbTab
Else
WScript.StdOut.Write n
End If
n = n + 1
Next
WScript.StdOut.WriteLine
Next
'display the trasposed matrix
WScript.StdOut.WriteBlankLines(1)
WScript.StdOut.WriteLine "Transposed Matrix:"
For i = 0 To x
For j = 0 To y
If j < y Then
WScript.StdOut.Write matrix(i,j) & vbTab
Else
WScript.StdOut.Write matrix(i,j)
End If
Next
WScript.StdOut.WriteLine
Next
|
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #REXX | REXX | /*REXX pgm shows a network device's manufacturer based on the Media Access Control addr.*/
win_command = 'getmac' /*name of the Microsoft Windows command*/
win_command_options = '/v /fo list' /*options of " " " */
?3= 'Network Adapter:' /*search keywords for Network Adapter. */
?4= 'Physical Address:' /* " " " Physical Address.*/
upper ?3 ?4 /*uppercase in case for capitol letters*/
@.=; @.0= 0 /*just─in─case values for the keywords.*/
rc= 0 /* " " " value for the returnCode*/
address system win_command win_command_options with output stem @. /*issue command.*/
if rc\==0 then do /*display an error if not successful. */
say
say '***error*** from command: ' win_command win_command_options
say 'Return code was: ' rc
say
exit rc
end
MACaddr=. /*just─in─case value for the keyword. */
maker=. /* " " " " " " " */
do j=1 for @.0; $= @.j; upper $ /*parse each of the possible responses.*/
if left($, length(?3))=?3 then maker= subword(@.j, 3) /*is this the one?*/
if left($, length(?4))=?4 then MACaddr= word(@.j, 3) /* " " " " */
end /*k*/
/* [↑] Now, display good or bad stuff.*/
if maker=. | MACaddr==. then say 'MAC address manufacturer not found.'
else say 'manufacturer for MAC address ' MACaddr " is " maker
exit 0 /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #C.2B.2B | C++ | #include <array>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
int main()
{
constexpr std::array<const char*, 20> answers = {
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes - definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."
};
std::string input;
std::srand(std::time(nullptr));
while (true) {
std::cout << "\n? : ";
std::getline(std::cin, input);
if (input.empty()) {
break;
}
std::cout << answers[std::rand() % answers.size()] << '\n';
}
} |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Buffer DataMem as Long*10
Return DataMem, 1:=500 ' second Long
Print Eval(DataMem, 1)+5100+5=5605
\\ Now we do math executing machine code
Buffer Code ExecMem as byte*1024
Address=0
EmbLong(0xb8, 5100) ' mov eax,5100
EmbByteByte(0x83, 0xC0, 5) ' add eax,0x5
EmbByteLong(0x3,0x5, DataMem(1)) ' add eax, [DataMem(1)]
EmbLong(0xa3, DataMem(0)) ' mov [DataMem(0)], eax
\\ split rem to execute xor eax eax (eax=0)
Rem : EmbByte(0x31, 0xC0) ' xor eax, eax
Ret() ' Return
\\
Try ok {
Execute Code ExecMem, 0
}
\\If Eax <>0 then we get error, so we read error as Uint()
\\ Error read once then change to zero
m=Uint(Error)
\\ Hex is Print Hexadecimal for unsigned numbers
Hex m
Print m=5605
Print Error=0, ok=False
Print Eval(DataMem, 0)=5605, Eval(DataMem, 0)
\\ sub used as Exit here
Sub Ret()
Return ExecMem, Address:=0xC3
Address++
End Sub
Sub EmbByteByte()
Return ExecMem, Address:=Number, Address+1:=Number, Address+2:=Number
Address+=3
End Sub
Sub EmbByte()
Return ExecMem, Address:=Number, Address+1:=Number
Address+=2
End Sub
Sub EmbLong()
Return ExecMem, Address:=Number, Address+1:=Number as Long
Address+=5
End Sub
Sub EmbByteLong()
Return ExecMem, Address:=Number, Address+1:=Number, Address+2:=Number as Long
Address+=6
End Sub
}
CheckIt
|
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Nim | Nim | import posix
let MAP_ANONYMOUS {.importc: "MAP_ANONYMOUS", header: "<sys/mman.h>".}: cint
proc test(a, b: cint): cint =
# mov EAX, [ESP+4]
# add EAX, [ESP+8]
# ret
var code = [0x8B'u8, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3]
# create an executable buffer
var buf = mmap(nil, sizeof(code), PROT_READ or PROT_WRITE or PROT_EXEC,
MAP_PRIVATE or MAP_ANONYMOUS, -1, 0)
# copy code to the buffer
copyMem(buf, addr code[0], sizeof(code))
# run code
result = cast[proc(a, b: cint): cint {.nimcall.}](buf)(a, b)
# free buffer
discard munmap(buf, sizeof(code))
echo test(7, 12) |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Racket | Racket |
#lang racket
(require racket/draw)
(define (iterations a z i)
(define z′ (+ (* z z) a))
(if (or (= i 255) (> (magnitude z′) 2))
i
(iterations a z′ (add1 i))))
(define (iter->color i)
(if (= i 255)
(make-object color% "black")
(make-object color% (* 5 (modulo i 15)) (* 32 (modulo i 7)) (* 8 (modulo i 31)))))
(define (mandelbrot width height)
(define target (make-bitmap width height))
(define dc (new bitmap-dc% [bitmap target]))
(for* ([x width] [y height])
(define real-x (- (* 3.0 (/ x width)) 2.25))
(define real-y (- (* 2.5 (/ y height)) 1.25))
(send dc set-pen (iter->color (iterations (make-rectangular real-x real-y) 0 0)) 1 'solid)
(send dc draw-point x y))
(send target save-file "mandelbrot.png" 'png))
(mandelbrot 300 200)
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Tailspin | Tailspin |
operator (A matmul B)
$A -> \[i](
$B(1) -> \[j](@: 0;
1..$B::length -> @: $@ + $A($i;$) * $B($;$j);
$@ !\) !
\) !
end matmul
templates printMatrix&{w:}
templates formatN
@: [];
$ -> #
'$@ -> $::length~..$w -> ' ';$@(last..1:-1)...;' !
when <1..> do ..|@: $ mod 10; $ ~/ 10 -> #
when <=0?($@ <[](0)>)> do ..|@: 0;
end formatN
$... -> '|$(1) -> formatN;$(2..last)... -> ', $ -> formatN;';|
' !
end printMatrix
def a: [[1, 2, 3], [4, 5, 6]];
'a:
' -> !OUT::write
$a -> printMatrix&{w:2} -> !OUT::write
def b: [[0, 1], [2, 3], [4, 5]];
'
b:
' -> !OUT::write
$b -> printMatrix&{w:2} -> !OUT::write
'
axb:
' -> !OUT::write
($a matmul $b) -> printMatrix&{w:2} -> !OUT::write
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Visual_Basic | Visual Basic | Option Explicit
'----------------------------------------------------------------------
Function TransposeMatrix(InitMatrix() As Long, TransposedMatrix() As Long)
Dim l1 As Long, l2 As Long, u1 As Long, u2 As Long, r As Long, c As Long
l1 = LBound(InitMatrix, 1)
l2 = LBound(InitMatrix, 2)
u1 = UBound(InitMatrix, 1)
u2 = UBound(InitMatrix, 2)
ReDim TransposedMatrix(l2 To u2, l1 To u1)
For r = l1 To u1
For c = l2 To u2
TransposedMatrix(c, r) = InitMatrix(r, c)
Next c
Next r
End Function
'----------------------------------------------------------------------
Sub PrintMatrix(a() As Long)
Dim l1 As Long, l2 As Long, u1 As Long, u2 As Long, r As Long, c As Long
Dim s As String * 8
l1 = LBound(a(), 1)
l2 = LBound(a(), 2)
u1 = UBound(a(), 1)
u2 = UBound(a(), 2)
For r = l1 To u1
For c = l2 To u2
RSet s = Str$(a(r, c))
Debug.Print s;
Next c
Debug.Print
Next r
End Sub
'----------------------------------------------------------------------
Sub TranspositionDemo(ByVal DimSize1 As Long, ByVal DimSize2 As Long)
Dim r, c, cc As Long
Dim a() As Long
Dim b() As Long
cc = DimSize2
DimSize1 = DimSize1 - 1
DimSize2 = DimSize2 - 1
ReDim a(0 To DimSize1, 0 To DimSize2)
For r = 0 To DimSize1
For c = 0 To DimSize2
a(r, c) = (cc * r) + c + 1
Next c
Next r
Debug.Print "initial matrix:"
PrintMatrix a()
TransposeMatrix a(), b()
Debug.Print "transposed matrix:"
PrintMatrix b()
End Sub
'----------------------------------------------------------------------
Sub Main()
TranspositionDemo 3, 3
TranspositionDemo 3, 7
End Sub |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #Ring | Ring |
# Project: MAC Vendor Lookup
load "stdlib.ring"
macs = ["FC-A1-3E","FC:FB:FB:01:FA:21","88:53:2E:67:07:BE","D4:F4:6F:C9:EF:8D"]
for mac = 1 to len(macs)
lookupvendor(macs[mac])
next
func lookupvendor(mac)
url = download("api.macvendors.com/" + mac)
see url + nl
|
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #Ruby | Ruby | require 'net/http'
arr = ['88:53:2E:67:07:BE', 'FC:FB:FB:01:FA:21', 'D4:F4:6F:C9:EF:8D', '23:45:67']
arr.each do |addr|
vendor = Net::HTTP.get('api.macvendors.com', "/#{addr}/") rescue nil
puts "#{addr} #{vendor}"
end |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #Rust | Rust | extern crate reqwest;
use std::{thread, time};
fn get_vendor(mac: &str) -> Option<String> {
let mut url = String::from("http://api.macvendors.com/");
url.push_str(mac);
let url_ref = &url;
match reqwest::get(url_ref) {
Ok(mut res) => match res.text() {
Ok(text) => {
if text.contains("Not Found") {
Some("N/A".to_string())
} else {
Some(text)
}
}
Err(e) => {
println!("{:?}", e);
None
}
},
Err(e) => {
println!("{:?}", e);
None
}
}
}
fn main() {
let duration = time::Duration::from_millis(1000);
match get_vendor("88:53:2E:67:07:BE") {
None => println!("Error!"),
Some(text) => println!("{}", text),
}
thread::sleep(duration);
match get_vendor("FC:FB:FB:01:FA:21") {
None => println!("Error!"),
Some(text) => println!("{}", text),
}
thread::sleep(duration);
match get_vendor("FC-A1-3E") {
None => println!("Error!"),
Some(text) => println!("{}", text),
}
thread::sleep(duration);
match get_vendor("abcdefg") {
None => println!("Error!"),
Some(text) => println!("{}", text),
}
}
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #C.23 | C# |
using System;
namespace newProg
{
class Program
{
static void Main(string[] args)
{
string[] answers =
{
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes – definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."
};
while (true)
{
Random rnd = new Random();
int result = rnd.Next(0, 19);
Console.WriteLine("Magic 8 Ball! Ask question and hit a key for the answer!");
string inp = Console.ReadLine();
Console.WriteLine(answers[result]);
}
}
}
}
|
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #PARI.2FGP | PARI/GP | #include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <pari/pari.h>
int
test(int a, int b)
{
char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};
void *buf;
int c;
/* copy code to executable buffer */
buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANON,-1,0);
memcpy (buf, code, sizeof(code));
/* run code */
c = ((int (*) (int, int))buf)(a, b);
/* free buffer */
munmap (buf, sizeof(code));
return c;
}
void
init_auto(void)
{
pari_printf("%d\n", test(7,12));
return 0;
} |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Raku | Raku | constant @color_map = map ~*.comb(/../).map({:16($_)}), <
000000 0000fc 4000fc 7c00fc bc00fc fc00fc fc00bc fc007c fc0040 fc0000 fc4000
fc7c00 fcbc00 fcfc00 bcfc00 7cfc00 40fc00 00fc00 00fc40 00fc7c 00fcbc 00fcfc
00bcfc 007cfc 0040fc 7c7cfc 9c7cfc bc7cfc dc7cfc fc7cfc fc7cdc fc7cbc fc7c9c
fc7c7c fc9c7c fcbc7c fcdc7c fcfc7c dcfc7c bcfc7c 9cfc7c 7cfc7c 7cfc9c 7cfcbc
7cfcdc 7cfcfc 7cdcfc 7cbcfc 7c9cfc b4b4fc c4b4fc d8b4fc e8b4fc fcb4fc fcb4e8
fcb4d8 fcb4c4 fcb4b4 fcc4b4 fcd8b4 fce8b4 fcfcb4 e8fcb4 d8fcb4 c4fcb4 b4fcb4
b4fcc4 b4fcd8 b4fce8 b4fcfc b4e8fc b4d8fc b4c4fc 000070 1c0070 380070 540070
700070 700054 700038 70001c 700000 701c00 703800 705400 707000 547000 387000
1c7000 007000 00701c 007038 007054 007070 005470 003870 001c70 383870 443870
543870 603870 703870 703860 703854 703844 703838 704438 705438 706038 707038
607038 547038 447038 387038 387044 387054 387060 387070 386070 385470 384470
505070 585070 605070 685070 705070 705068 705060 705058 705050 705850 706050
706850 707050 687050 607050 587050 507050 507058 507060 507068 507070 506870
506070 505870 000040 100040 200040 300040 400040 400030 400020 400010 400000
401000 402000 403000 404000 304000 204000 104000 004000 004010 004020 004030
004040 003040 002040 001040 202040 282040 302040 382040 402040 402038 402030
402028 402020 402820 403020 403820 404020 384020 304020 284020 204020 204028
204030 204038 204040 203840 203040 202840 2c2c40 302c40 342c40 3c2c40 402c40
402c3c 402c34 402c30 402c2c 40302c 40342c 403c2c 40402c 3c402c 34402c 30402c
2c402c 2c4030 2c4034 2c403c 2c4040 2c3c40 2c3440 2c3040
>;
constant MAX_ITERATIONS = 50;
my $width = my $height = +(@*ARGS[0] // 31);
sub cut(Range $r, UInt $n where $n > 1) {
$r.min, * + ($r.max - $r.min) / ($n - 1) ... $r.max
}
my @re = cut(-2 .. 1/2, $height);
my @im = cut( 0 .. 5/4, $width div 2 + 1) X* 1i;
sub mandelbrot(Complex $z is copy, Complex $c) {
for 1 .. MAX_ITERATIONS {
$z = $z*$z + $c;
return $_ if $z.abs > 2;
}
return 0;
}
say "P3";
say "$width $height";
say "255";
for @re -> $re {
put @color_map[|.reverse, |.[1..*]][^$width] given
my @ = map &mandelbrot.assuming(0i, *), $re «+« @im;
} |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Tcl | Tcl | package require Tcl 8.5
namespace path ::tcl::mathop
proc matrix_multiply {a b} {
lassign [size $a] a_rows a_cols
lassign [size $b] b_rows b_cols
if {$a_cols != $b_rows} {
error "incompatible sizes: a($a_rows, $a_cols), b($b_rows, $b_cols)"
}
set temp [lrepeat $a_rows [lrepeat $b_cols 0]]
for {set i 0} {$i < $a_rows} {incr i} {
for {set j 0} {$j < $b_cols} {incr j} {
set sum 0
for {set k 0} {$k < $a_cols} {incr k} {
set sum [+ $sum [* [lindex $a $i $k] [lindex $b $k $j]]]
}
lset temp $i $j $sum
}
}
return $temp
} |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Wortel | Wortel | @zipm [[1 2 3] [4 5 6] [7 8 9]] |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Wren | Wren | import "/matrix" for Matrix
import "/fmt" for Fmt
var m = Matrix.new([
[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]
])
System.print("Original:\n")
Fmt.mprint(m, 2, 0)
System.print("\nTransposed:\n")
Fmt.mprint(m.transpose, 2, 0) |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #Scala | Scala | object LookUp extends App {
val macs = Seq("FC-A1-3E", "FC:FB:FB:01:FA:21", "88:53:2E:67:07:BE", "D4:F4:6F:C9:EF:8D")
def lookupVendor(mac: String) =
scala.io.Source.fromURL("""http://api.macvendors.com/""" + mac, "UTF-8").mkString
macs.foreach(mac => println(lookupVendor(mac)))
} |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #Tcl | Tcl | package require http
# finally is a bit like go's defer
proc finally args {
tailcall trace add variable :#finally#: unset [list apply [list args $args]]
}
# basic wrapper for http::geturl
proc geturl {url} {
set tok [::http::geturl $url]
finally ::http::cleanup $tok
::http::data $tok
}
proc maclookup {mac} {
geturl http://api.macvendors.com/$mac
}
foreach mac {00-14-22-01-23-45 88:53:2E:67:07:BE} {
puts "$mac\t[maclookup $mac]"
} |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #CFEngine | CFEngine |
#!/var/cfengine/bin/cf-agent --no-lock
bundle agent __main__
{
methods: "rosettacode_org:magic_8_ball";
}
body file control
{
namespace => "rosettacode_org";
}
bundle agent magic_8_ball
{
vars:
"_responses"
slist => {
"It is certain", "It is decidedly so", "Without a doubt",
"Yes definitely", "You may rely on it", "As I see it yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful",
};
"_selected_response"
int => randomint( 0, length( _responses) ),
unless => isvariable( "$(this.namespace):$(this.promiser)" );
"_consideration_time"
int => randomint( 3, 5),
unless => isvariable( "$(this.namespace):$(this.promiser)" );
commands:
"/bin/sleep $(_consideration_time)"
inform => "false",
handle => "consider",
depends_on => { "think" },
comment => "This magic 8 ball takes a few seconds to consider the answer
after you bring your question to mind.";
reports:
"Think about your question ..."
handle => "think";
"Response: $(with)"
with => nth( _responses, $(_selected_response) ),
depends_on => { "consider" };
}
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #Clojure | Clojure |
(def responses
["It is certain" "It is decidedly so" "Without a doubt"
"Yes, definitely" "You may rely on it" "As I see it, yes"
"Most likely" "Outlook good" "Signs point to yes" "Yes"
"Reply hazy, try again" "Ask again later"
"Better not tell you now" "Cannot predict now"
"Concentrate and ask again" "Don't bet on it"
"My reply is no" "My sources say no" "Outlook not so good"
"Very doubtful"])
(do
(println "Ask a question. ")
(read-line)
(println (rand-nth responses)))
|
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Pascal | Pascal | Program Example66;
{Inspired... program to demonstrate the MMap function. Freepascal docs }
Uses
BaseUnix,Unix;
const
code : array[0..9] of byte = ($8B, $44, $24, $4, $3, $44, $24, $8, $C3, $00);
a :longInt= 12;
b :longInt= 7;
type
tDummyFunc = function(a,b:LongInt):LongInt;cdecl;
Var
Len,k : cint;
P : Pointer;
begin
len := sizeof(code);
P:= fpmmap(nil,
len+1 ,
PROT_READ OR PROT_WRITE OR PROT_EXEC,
MAP_ANONYMOUS OR MAP_PRIVATE,
-1, // for MAP_ANONYMOUS
0);
If P = Pointer(-1) then
Halt(4);
for k := 0 to len-1 do
pChar(p)[k] := char(code[k]);
k := tDummyFunc(P)(a,b);
Writeln(a,'+',b,' = ',k);
if fpMUnMap(P,Len)<>0 Then
Halt(fpgeterrno);
end. |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #REXX | REXX | /*REXX program generates and displays a Mandelbrot set as an ASCII art character image.*/
@ = '>=<;:9876543210/.-,+*)(''&%$#"!' /*the characters used in the display. */
Xsize = 59; minRE = -2; maxRE = +1; stepX = (maxRE-minRE) / Xsize
Ysize = 21; minIM = -1; maxIM = +1; stepY = (maxIM-minIM) / Ysize
do y=0 for ysize; im=minIM + stepY*y
$=
do x=0 for Xsize; re=minRE + stepX*x; zr=re; zi=im
do n=0 for 30; a=zr**2; b=zi**2; if a+b>4 then leave
zi=zr*zi*2 + im; zr=a-b+re
end /*n*/
$=$ || substr(@, n+1, 1) /*append number (as a char) to $ string*/
end /*x*/
say $ /*display a line of character output.*/
end /*y*/ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #TI-83_BASIC | TI-83 BASIC | Disp [A]*[B] |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #XPL0 | XPL0 | proc Transpose(M, R, C, N); \Transpose matrix M to N
int M, R, C, N; \rows and columns
int I, J;
[for I:= 0 to R-1 do
for J:= 0 to C-1 do
N(J,I):= M(I,J);
];
proc ShowMat(M, R, C); \Display matrix M
int M, R, C; \rows and columns
int I, J;
[for I:= 0 to R-1 do
[for J:= 0 to C-1 do
RlOut(0, float(M(I,J)));
CrLf(0);
];
];
int M, N(4,3);
[M:= [[1, 2, 3, 4], \3 rows by 4 columns
[5, 6, 7, 8],
[9,10,11,12]];
Format(4, 0);
ShowMat(M, 3, 4);
CrLf(0);
Transpose(M, 3, 4, N);
ShowMat(N, 4, 3);
] |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #UNIX_Shell | UNIX Shell |
macList=("88:53:2E:67:07:BE" "D4:F4:6F:C9:EF:8D" "FC:FB:FB:01:FA:21" "4c:72:b9:56:fe:bc" "00-14-22-01-23-45");for burger in ${macList[@]};do curl http://api.macvendors.com/$burger && sleep 5 && echo;done
|
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #VBScript | VBScript |
a=array("00-20-6b-ba-d0-cb","00-40-ae-04-87-86")
set WebRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
for each MAC in a
if b<>0 then wscript.echo "Spacing next request...": wscript.sleep 2000
WebRequest.Open "GET", "http://api.macvendors.com/"& mac,1
WebRequest.Send()
WebRequest.WaitForResponse
b=b+1
wscript.echo mac & " -> " & WebRequest.ResponseText
next
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #CMake | CMake | CMAKE_MINIMUM_REQUIRED(VERSION 3.6)
PROJECT(EightBall)
SET(CMAKE_DISABLE_SOURCE_CHANGES ON)
SET(CMAKE_DISABLE_IN_SOURCE_BUILD ON)
LIST(APPEND RESPONSES "It is certain." "It is decidedly so." "Without a doubt.")
LIST(APPEND RESPONSES "Yes - definitely." "You may rely on it.")
LIST(APPEND RESPONSES "As I see it yes." "Most likely." "Outlook good.")
LIST(APPEND RESPONSES "Yes." "Signs point to yes." "Reply hazy try again.")
LIST(APPEND RESPONSES "Ask again later." "Better not tell you now.")
LIST(APPEND RESPONSES "Cannot predict now." "Concentrate and ask again.")
LIST(APPEND RESPONSES "Don't count on it." "My reply is no.")
LIST(APPEND RESPONSES "My sources say no." "Outlook not so good." "Very doubtful.")
FUNCTION(RANDOM_RESPONSE)
STRING(RANDOM LENGTH 1 ALPHABET 01 TENS)
STRING(RANDOM LENGTH 1 ALPHABET 0123456789 UNITS)
MATH(EXPR INDEX "${TENS}${UNITS}")
LIST(GET RESPONSES ${INDEX} RESPONSE)
MESSAGE(STATUS "Question: ${QUESTION}")
MESSAGE(STATUS "Response: ${RESPONSE}")
ENDFUNCTION(RANDOM_RESPONSE)
OPTION(QUESTION "User's input question" "")
MESSAGE("===================== 8 Ball =====================")
IF(NOT QUESTION)
MESSAGE(STATUS "Welcome to 8 ball! Please provide a question ")
MESSAGE(STATUS "using the flag -DQUESTION=\"my question\"")
ELSE()
RANDOM_RESPONSE()
ENDIF()
MESSAGE("==================================================")
ADD_CUSTOM_TARGET(${PROJECT_NAME} ALL)
|
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Phix | Phix | atom mem = allocate(9)
poke(mem,{#8B,#44,#24,#04,#03,#44,#24,#08,#C3})
constant mfunc = define_c_func({},mem,{C_INT,C_INT},C_INT)
?c_func(mfunc,{12,7})
free(mem)
|
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #PicoLisp | PicoLisp | (setq P
(struct (native "@" "malloc" 'N 39) 'N
# Align
144 # nop
144 # nop
# Prepare stack
106 12 # pushq $12
184 7 0 0 0 # mov $7, %eax
72 193 224 32 # shl $32, %rax
80 # pushq %rax
# Rosetta task code
139 68 36 4 3 68 36 8
# Get result
76 137 227 # mov %r12, %rbx
137 195 # mov %eax, %ebx
72 193 227 4 # shl $4, %rbx
128 203 2 # orb $2, %bl
# Clean up stack
72 131 196 16 # add $16, %rsp
# Return
195 ) # ret
foo (>> 4 P) )
# Execute
(println (foo))
# Free memory
(native "@" "free" NIL P) |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Ring | Ring |
load "guilib.ring"
new qapp
{
win1 = new qwidget() {
setwindowtitle("Mandelbrot set")
setgeometry(100,100,500,500)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1) {
setgeometry(200,400,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
new qpainter() {
begin(p1)
setpen(pen)
x1=300 y1=250
i1=-1 i2=1 r1=-2 r2=1
s1=(r2-r1)/x1 s2=(i2-i1)/y1
for y=0 to y1
i3=i1+s2*y
for x=0 to x1
r3=r1+s1*x z1=r3 z2=i3
for n=0 to 30
a=z1*z1 b=z2*z2
if a+b>4 exit ok
z2=2*z1*z2+i3 z1=a-b+r3
next
if n != 31 drawpoint(x,y) ok
next
next
endpaint()
}
label1 { setpicture(p1) show() }
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #TI-89_BASIC | TI-89 BASIC | [1,2; 3,4; 5,6; 7,8] → m1
[1,2,3; 4,5,6] → m2
m1 * m2 |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Yabasic | Yabasic | dim matriz(4,5)
dim mtranspuesta(5,4)
for fila = 1 to arraysize(matriz(), 1)
for columna = 1 to arraysize(matriz(), 2)
read matriz(fila, columna)
print matriz(fila, columna);
mtranspuesta(columna, fila) = matriz(fila, columna)
next columna
print
next fila
print
for fila = 1 to arraysize(mtranspuesta(), 1)
for columna = 1 to arraysize(mtranspuesta(), 2)
print mtranspuesta(fila, columna);
next columna
print
next fila
end
data 78,19,30,12,36
data 49,10,65,42,50
data 30,93,24,78,10
data 39,68,27,64,29 |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
GSL.Matrix(2,3).set(1,2,3, 4,5,6).transpose().format(5).println(); // in place
println("---");
GSL.Matrix(2,2).set(1,2, 3,4).transpose().format(5).println(); // in place
println("---");
GSL.Matrix(3,1).set(1,2,3).transpose().format(5).println(); // in place |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #Wren | Wren | /* mac_vendor_lookup.wren */
class MAC {
foreign static lookup(address)
}
System.print(MAC.lookup("FC:FB:FB:01:FA:21"))
for (i in 1..1e8) {} // slow down request
System.print(MAC.lookup("23:45:67")) |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #zkl | zkl | var [const] CURL=Import("zklCurl"); // libcurl
const MAC_VENDORS="http://api.macvendors.com/";
fcn lookUp(macAddress){
httpAddr:=MAC_VENDORS + macAddress;
vender:=CURL().get(httpAddr); //-->(Data,bytes of header,bytes of trailer)
vender=vender[0].del(0,vender[1]); // remove HTTP header
vender.text; // Data --> String (Data is a byte bucket)
} |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #Commodore_BASIC | Commodore BASIC |
10 dim f$(19):for i=0 to 19:read f$(i):next
20 print chr$(147);chr$(14)
30 print "Press any key to reveal your fortune."
40 print:print "Press Q to quit.":print
50 fo=int(rnd(1)*20):get k$:if k$="" then 50
60 if k$="q" then print "Good luck!":end
70 print "Your fortune reads:"
80 print spc(5);f$(fo):print
90 print "Again? (Y/N)"
100 get k$:if k$="" then 100
110 if k$="y" then goto 20
120 end
1000 data "It is certain.","It is decidedly so."
1010 data "Without a doubt.","Yes – definitely."
1020 data "You may rely on it.","As I see it, yes."
1030 data "Most likely.","Outlook good.","Yes."
1040 data "Signs point to yes.","Reply hazy, try again."
1050 data "Ask again later.","Better not tell you now."
1060 data "Cannot predict now.","Concentrate and ask again."
1070 data "Don't count on it.","My reply is no."
1080 data "My sources say no.","Outlook not so good."
1090 data "Very doubtful."
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #D | D | import std.random, std.stdio, std.string;
const string[] responses = ["It is certain", "It is decidedly so",
"Without a doubt", "Yes, definitely",
"You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes",
"Yes", "Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no",
"Outlook not so good", "Very doubtful"];
void main()
{
string question = "";
auto rnd = Random(unpredictableSeed);
int index = -1;
writeln("Welcome to 8 ball! Please enter your question to ");
write("find the answers you seek.");
write("Type 'quit' to exit.", "\n\n");
while(true)
{
write("Question: ");
question = stdin.readln();
if(strip(question) == "quit")
{
break;
}
write("Response: ");
index = uniform(0, 20, rnd);
write(responses[index], "\n\n");
}
}
|
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #PL.2FM | PL/M | 100H:
/* 8080 MACHINE CODE TO ADD TWO BYTES:
79 MOV A,C ; LOAD FIRST ARG INTO ACCUMULATOR
83 ADD E ; ADD SECOND ARG TO ACCUMULATOR
C9 RET ; RETURN */
DECLARE ADD$8080 DATA (79H, 83H, 0C9H);
/* THE 8080 PL/M CALLING CONVENTION IS THAT THE
NEXT-TO-LAST ARG IS PUT IN (B)C, THE LAST ARG IN (D)E.
(THE REST ARE IN MEMORY BUT WE DO NOT NEED ANY MORE.)
THE RETURN ARGUMENT SHOULD BE IN THE ACCUMULATOR.
WE CAN DEFINE A WRAPPER PROCEDURE TO DECLARE THE
TYPES OF THE ARGUMENTS. */
EXEC$ADD: PROCEDURE (A,B) BYTE;
DECLARE (A,B) BYTE;
/* WE CAN 'GO TO' CONSTANTS OR VARIABLES, BUT NOT TO
EXPRESSIONS. SO WE HAVE TO FETCH THE ADDRESS FIRST. */
DECLARE LOC ADDRESS;
LOC = .ADD$8080;
GO TO LOC;
END EXEC$ADD;
/* IN FACT, PL/M DOES NOT COME WITH ANY STANDARD LIBARIES.
IT IS FROM BEFORE THE TIME THAT YOU COULD ASSUME THERE
WOULD EVEN BE AN OPERATING SYSTEM, THOUGH CP/M
(THE PREDECESSOR TO DOS) WOULD QUICKLY BECOME STANDARD.
WE NEED TO USE THIS EXACT TRICK TO GET CP/M TO PRINT THE
RESULT TO THE OUTPUT. LUCKILY (AND NOT COINCIDENTALLY),
THE CP/M SYSCALL ENTRY POINT IS COMPATIBLE WITH THE
PL/M CALLING CONVENTION. */
BDOS: PROCEDURE (FUNC, ARG);
DECLARE FUNC BYTE;
DECLARE ARG ADDRESS;
/* 5 IS THE CP/M BDOS ENTRY POINT */
GO TO 5;
END BDOS;
/* WE ALSO NEED OUR OWN NUMBER OUTPUT ROUTINE. WE CAN WRITE
IT IN PL/M, THEN USE THE ABOVE ROUTINE TO TELL CP/M
TO PRINT THE RESULT. */
PRINT$NUMBER: PROCEDURE(N);
DECLARE S (4) BYTE INITIAL ('...$');
DECLARE P ADDRESS;
DECLARE (N, C BASED P) BYTE;
/* EXTRACT EACH DIGIT AND WRITE THEM BACKWARDS TO A STRING */
P = .S(3);
DIGIT:
P = P-1;
C = (N MOD 10) + '0';
N = N/10;
IF N > 0 THEN GO TO DIGIT;
/* TELL CP/M TO PRINT THE RESULTING STRING */
CALL BDOS(9, P);
END PRINT$NUMBER;
/* USING OUR OWN MACHINE CODE WORKS IN THE SAME WAY */
CALL PRINT$NUMBER( EXEC$ADD( 7, 12) ); /* THIS PRINTS 19 */
CALL BDOS(0,0); /* EXIT */
EOF |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #PureBasic | PureBasic | CompilerIf #PB_Compiler_Processor <> #PB_Processor_x86
CompilerError "Code requires a 32-bit processor."
CompilerEndIf
; Machine code using the Windows API
Procedure MachineCodeVirtualAlloc(a,b)
*vm = VirtualAlloc_(#Null,?ecode-?scode,#MEM_COMMIT,#PAGE_EXECUTE_READWRITE)
If(*vm)
CopyMemory(?scode, *vm, ?ecode-?scode)
eax_result=CallFunctionFast(*vm,a,b)
VirtualFree_(*vm,0,#MEM_RELEASE)
ProcedureReturn eax_result
EndIf
EndProcedure
rv=MachineCodeVirtualAlloc( 7, 12)
MessageRequester("MachineCodeVirtualAlloc",Str(rv)+Space(50),#PB_MessageRequester_Ok)
#HEAP_CREATE_ENABLE_EXECUTE=$00040000
Procedure MachineCodeHeapCreate(a,b)
hHeap=HeapCreate_(#HEAP_CREATE_ENABLE_EXECUTE,?ecode-?scode,?ecode-?scode)
If(hHeap)
CopyMemory(?scode, hHeap, ?ecode-?scode)
eax_result=CallFunctionFast(hHeap,a,b)
HeapDestroy_(hHeap)
ProcedureReturn eax_result
EndIf
EndProcedure
rv=MachineCodeHeapCreate(7,12)
MessageRequester("MachineCodeHeapCreate",Str(rv)+Space(50),#PB_MessageRequester_Ok)
End
; 8B442404 mov eax,[esp+4]
; 03442408 add eax,[esp+8]
; C20800 ret 8
DataSection
scode:
Data.a $8B,$44,$24,$04,$03,$44,$24,$08,$C2,$08,$00
ecode:
EndDataSection |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Ruby | Ruby | require 'complex'
def mandelbrot(a)
Array.new(50).inject(0) { |z,c| z*z + a }
end
(1.0).step(-1,-0.05) do |y|
(-2.0).step(0.5,0.0315) do |x|
print mandelbrot(Complex(x,y)).abs < 2 ? '*' : ' '
end
puts
end |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Transd | Transd | #lang transd
MainModule: {
_start: (λ (with n 5
A (for i in Range(n) project (for k in Range(n) project k))
B (for i in Range(n) project (for k in Range(n) project (- n k)))
C (for i in Range(n) project (for k in Range(n) project 0))
(for i in Range( n ) do
(for j in Range( n ) do
(for k in Range( n ) do
(+= (get (get C i) j) (* (get (get A i) k) (get (get B k) j)))
)))
(lout C))
)
} |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #zonnon | zonnon |
module MatrixOps;
type
Matrix = array {math} *,* of integer;
procedure WriteMatrix(x: array {math} *,* of integer);
var
i,j: integer;
begin
for i := 0 to len(x,0) - 1 do
for j := 0 to len(x,1) - 1 do
write(x[i,j]);
end;
writeln;
end
end WriteMatrix;
procedure Transposition;
var
m,x: Matrix;
begin
m := [[1,2,3],[3,4,5]]; (* matrix initialization *)
x := !m; (* matrix trasposition *)
WriteMatrix(x);
end Transposition;
begin
Transposition;
end MatrixOps.
|
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #Zoea | Zoea |
program: mac_vendor_lookup
data: 'http://api.macvendors.com/'
input: 'D4:F4:6F:C9:EF:8D'
derive: 'http://api.macvendors.com/D4:F4:6F:C9:EF:8D'
output: 'Apple, Inc.'
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #Delphi | Delphi |
program Magic_8_ball;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
windows;
// https://stackoverflow.com/questions/29794559/delphi-console-xe7-clearscreen
procedure ClearScreen;
var
stdout: THandle;
csbi: TConsoleScreenBufferInfo;
ConsoleSize: DWORD;
NumWritten: DWORD;
Origin: TCoord;
begin
stdout := GetStdHandle(STD_OUTPUT_HANDLE);
Win32Check(stdout <> INVALID_HANDLE_VALUE);
Win32Check(GetConsoleScreenBufferInfo(stdout, csbi));
ConsoleSize := csbi.dwSize.X * csbi.dwSize.Y;
Origin.X := 0;
Origin.Y := 0;
Win32Check(FillConsoleOutputCharacter(stdout, ' ', ConsoleSize, Origin, NumWritten));
Win32Check(FillConsoleOutputAttribute(stdout, csbi.wAttributes, ConsoleSize,
Origin, NumWritten));
Win32Check(SetConsoleCursorPosition(stdout, Origin));
end;
const
answers: array[0..19] of string = ('It is certain.', 'It is decidedly so.',
'Without a doubt.', 'Yes – definitely.', 'You may rely on it.',
'As I see it, yes.', 'Most likely.', 'Outlook good.', 'Yes.',
'Signs point to yes.', 'Reply hazy, try again.', 'Ask again later',
'Better not tell you now.', 'Cannot predict now.',
'Concentrate and ask again.', 'Don''t count on it.', 'My reply is no.',
'My sources say no.', 'Outlook not so good.', 'Very doubtful.');
begin
Randomize;
while True do
begin
writeln('Magic 8 Ball! Ask question and hit ENTER key for the answer!');
readln;
ClearScreen;
writeln(answers[Random(length(answers))], #10#10#10);
writeln('(Hit ENTER key to ask again)');
readln;
ClearScreen;
end;
end. |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Python | Python | import ctypes
import os
from ctypes import c_ubyte, c_int
code = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])
code_size = len(code)
# copy code into an executable buffer
if (os.name == 'posix'):
import mmap
executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
# we must keep a reference to executable_map until the call, to avoid freeing the mapped memory
executable_map.write(code)
# the mmap object won't tell us the actual address of the mapping, but we can fish it out by allocating
# some ctypes object over its buffer, then asking the address of that
func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map))
elif (os.name == 'nt'):
# the mmap module doesn't support protection flags on Windows, so execute VirtualAlloc instead
code_buffer = ctypes.create_string_buffer(code)
PAGE_EXECUTE_READWRITE = 0x40 # Windows constants that would usually come from header files
MEM_COMMIT = 0x1000
executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)
if (executable_buffer_address == 0):
print('Warning: Failed to enable code execution, call will likely cause a protection fault.')
func_address = ctypes.addressof(code_buffer)
else:
ctypes.memmove(executable_buffer_address, code_buffer, code_size)
func_address = executable_buffer_address
else:
# for other platforms, we just hope DEP isn't enabled
code_buffer = ctypes.create_string_buffer(code)
func_address = ctypes.addressof(code_buffer)
prototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte) # build a function prototype from return type and argument types
func = prototype(func_address) # build an actual function from the prototype by specifying the address
res = func(7,12)
print(res)
|
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Rust | Rust | extern crate image;
extern crate num_complex;
use std::fs::File;
use num_complex::Complex;
fn main() {
let max_iterations = 256u16;
let img_side = 800u32;
let cxmin = -2f32;
let cxmax = 1f32;
let cymin = -1.5f32;
let cymax = 1.5f32;
let scalex = (cxmax - cxmin) / img_side as f32;
let scaley = (cymax - cymin) / img_side as f32;
// Create a new ImgBuf
let mut imgbuf = image::ImageBuffer::new(img_side, img_side);
// Calculate for each pixel
for (x, y, pixel) in imgbuf.enumerate_pixels_mut() {
let cx = cxmin + x as f32 * scalex;
let cy = cymin + y as f32 * scaley;
let c = Complex::new(cx, cy);
let mut z = Complex::new(0f32, 0f32);
let mut i = 0;
for t in 0..max_iterations {
if z.norm() > 2.0 {
break;
}
z = z * z + c;
i = t;
}
*pixel = image::Luma([i as u8]);
}
// Save image
imgbuf.save("fractal.png").unwrap();
} |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #UNIX_Shell | UNIX Shell |
#!/bin/bash
DELAY=0 # increase this if printing of matrices should be slower
echo "This script takes two matrices, henceforth called A and B,
and returns their product, AB.
For the time being, matrices can have integer components only.
"
read -p "Number of rows of matrix A: " arows
read -p "Number of columns of matrix A: " acols
brows="$acols"
echo
echo "Number of rows of matrix B: "$brows
read -p "Number of columns of matrix B: " bcols
crows="$arows"
ccols="$bcols"
echo
echo "Number of rows of matrix AB: " $crows
echo "Number of columns of matrix AB: " $ccols
echo
echo
matrixa=( )
matrixb=( )
# input matrix A
maxlengtha=0
for ((row=1; row<=arows; row++)); do
for ((col=1; col<=acols; col++)); do
checkentry="false"
while [ "$checkentry" != "true" ]; do
read -p "Enter component A[$row, $col]: " number
index=$(((row-1)*acols+col))
matrixa[$index]="$number"
[ "${matrixa[$index]}" -eq "$number" ] && checkentry="true"
echo
done
entry="${matrixa[$index]}"
[ "${#entry}" -gt "$maxlengtha" ] && maxlengtha="${#entry}"
done
echo
done
# print matrix A to guard against errors
if [ "$maxlengtha" -le "5" ]; then
width=8
else
width=$((maxlengtha + 3))
fi
echo "This is matrix A:
"
for ((row=1; row<=arows; row++)); do
for ((col=1; col<=acols; col++)); do
index=$(((row-1)*acols+col))
printf "%${width}d" "${matrixa[$index]}"
sleep "$DELAY"
done
echo; echo # printf %s "\n\n" does not work...
done
echo
echo
# input matrix B
maxlengthb=0
for ((row=1; row<=brows; row++)); do
for ((col=1; col<=bcols; col++)); do
checkentry="false"
while [ "$checkentry" != "true" ]; do
read -p "Enter component B[$row, $col]: " number
index=$(((row-1)*bcols+col))
matrixb[$index]="$number"
[ "${matrixb[$index]}" -eq "$number" ] && checkentry="true"
echo
done
entry="${matrixb[$index]}"
[ "${#entry}" -gt "$maxlengthb" ] && maxlengthb="${#entry}"
done
echo
done
# print matrix B to guard against errors
if [ "$maxlengthb" -le "5" ]; then
width=8
else
width=$((maxlengthb + 3))
fi
echo "This is matrix B:
"
for ((row=1; row<=brows; row++)); do
for ((col=1; col<=bcols; col++)); do
index=$(((row-1)*bcols+col))
printf "%${width}d" "${matrixb[$index]}"
sleep "$DELAY"
done
echo; echo # printf %s "\n\n" does not work...
done
read -p "Hit enter to continue"
# calculate matrix C := AB
maxlengthc=0
time for ((row=1; row<=crows; row++)); do
for ((col=1; col<=ccols; col++)); do
# calculate component C[$row, $col]
runningtotal=0
for ((j=1; j<=acols; j++)); do
rowa="$row"
cola="$j"
indexa=$(((rowa-1)*acols+cola))
rowb="$j"
colb="$col"
indexb=$(((rowb-1)*bcols+colb))
entry_from_A=${matrixa[$indexa]}
entry_from_B=${matrixb[$indexb]}
subtotal=$((entry_from_A * entry_from_B))
((runningtotal+=subtotal))
done
number="$runningtotal"
# store component in the result array
index=$(((row-1)*ccols+col))
matrixc[$index]="$number"
entry="${matrixc[$index]}"
[ "${#entry}" -gt "$maxlengthc" ] && maxlengthc="${#entry}"
done
done
echo
read -p "Hit enter to continue"
echo
# print the matrix C
if [ "$maxlengthc" -le "5" ]; then
width=8
else
width=$((maxlengthc + 3))
fi
echo "The product matrix is:
"
for ((row=1; row<=crows; row++)); do
for ((col=1; col<=ccols; col++)); do
index=$(((row-1)*ccols+col))
printf "%${width}d" "${matrixc[$index]}"
sleep "$DELAY"
done
echo; echo # printf %s "\n\n" does not work...
done
echo
echo
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #Factor | Factor | USING: io kernel random sequences ;
IN: rosetta-code.magic-8-ball
CONSTANT: phrases {
"It is certain" "It is decidedly so" "Without a doubt"
"Yes, definitely" "You may rely on it" "As I see it, yes"
"Most likely" "Outlook good" "Signs point to yes" "Yes"
"Reply hazy, try again" "Ask again later"
"Better not tell you now" "Cannot predict now"
"Concentrate and ask again" "Don't bet on it"
"My reply is no" "My sources say no" "Outlook not so good"
"Very doubtful"
}
"Please enter your question or a blank line to quit." print
[ "? : " write flush readln empty? [ f ]
[ phrases random print t ] if ] loop |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #FreeBASIC | FreeBASIC | dim as string answer(0 to 19) = { "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes – definitely.",_
"You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.",_
"Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.",_
"Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.",_
"My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful." }
dim as string question
randomize timer
print "Q to quit."
do
input "What would you like to know? ", question
if ucase(question)="Q" then exit do
print answer(int(rnd*20))
print
loop |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Quackery | Quackery | /O> ( check that + and negate are operators (i.e. op-codes )
... ' + operator? ' negate operator? and if [ say "true"]
...
true
Stack empty.
/O> ( create a memory block large enough to hold them, )
... ( filled with zeros )
... 0 2 of
...
Stack: [ 0 0 ]
/O> ( poke the + operator into place )
... ' + swap 0 poke
...
Stack: [ + 0 ]
/O> ( poke the negate operator into place )
... ' negate swap 1 poke
...
Stack: [ + negate ]
/O> ( Using the phrase )
... ( )
... ( ' + ' negate join )
... ( )
... ( would be more idiomatic, but )
... ( the task specifies poking. )
Stack: [ + negate ]
/O> ( now put two numbers underneath it on the stack )
... 7 12 rot
...
Stack: 7 12 [ + negate ]
/O> ( and run the machine code )
... do
...
Stack: -19
/O> ( ta-da! )
|
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Racket | Racket | #lang racket/base
(require ffi/unsafe)
; set up access to racket internals
(define scheme-malloc-code
(get-ffi-obj 'scheme_malloc_code #f (_fun (len : _intptr) -> _pointer)))
(define scheme-free-code
(get-ffi-obj 'scheme_free_code #f (_fun _pointer -> _void)))
(define opcodes '(139 68 36 4 3 68 36 8 195))
(define code (scheme-malloc-code 64))
(for ([byte opcodes]
[i (in-naturals)])
(ptr-set! code _ubyte i byte))
(define function (cast code _pointer (_fun _ubyte _ubyte -> _ubyte)))
(function 7 12)
(scheme-free-code code) |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Sass.2FSCSS | Sass/SCSS |
$canvasWidth: 200;
$canvasHeight: 200;
$iterations: 20;
$xCorner: -2;
$yCorner: -1.5;
$zoom: 3;
$data: ()!global;
@mixin plot ($x,$y,$count){
$index: ($y * $canvasWidth + $x) * 4;
$r: $count * -12 + 255;
$g: $count * -12 + 255;
$b: $count * -12 + 255;
$data: append($data, $x + px $y + px 0 rgb($r,$g,$b), comma)!global;
}
@for $x from 1 to $canvasWidth {
@for $y from 1 to $canvasHeight {
$count: 0;
$size: 0;
$cx: $xCorner + (($x * $zoom) / $canvasWidth);
$cy: $yCorner + (($y * $zoom) / $canvasHeight);
$zx: 0;
$zy: 0;
@while $count < $iterations and $size <= 4 {
$count: $count + 1;
$temp: ($zx * $zx) - ($zy * $zy);
$zy: (2 * $zx * $zy) + $cy;
$zx: $temp + $cx;
$size: ($zx * $zx) + ($zy * $zy);
}
@include plot($x, $y, $count);
}
}
.set {
height: 1px;
width: 1px;
position: absolute;
top: 50%;
left: 50%;
transform: translate($canvasWidth*0.5px, $canvasWidth*0.5px);
box-shadow: $data;
}
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Ursala | Ursala | #import rat
a =
<
<1/1, 1/1, 1/1, 1/1>,
<2/1, 4/1, 8/1, 16/1>,
<3/1, 9/1, 27/1, 81/1>,
<4/1, 16/1, 64/1, 256/1>>
b =
<
< 4/1, -3/1, 4/3, -1/4>,
<-13/3, 19/4, -7/3, 11/24>,
< 3/2, -2/1, 7/6, -1/4>,
< -1/6, 1/4, -1/6, 1/24>>
mmult = *rK7lD *rlD sum:-0.+ product*p
#cast %qLL
test = mmult(a,b) |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #11l | 11l | F ludic(nmax = 100000)
V r = [1]
V lst = Array(2..nmax)
L !lst.empty
r.append(lst[0])
[Int] newlst
V step = lst[0]
L(i) 0 .< lst.len
I i % step != 0
newlst.append(lst[i])
lst = newlst
R r
V ludics = ludic()
print(‘First 25 ludic primes:’)
print(ludics[0.<25])
print("\nThere are #. ludic numbers <= 1000".format(sum(ludics.filter(l -> l <= 1000).map(l -> 1))))
print("\n2000'th..2005'th ludic primes:")
print(ludics[2000 - 1 .. 2004])
V n = 250
V triplets = ludics.filter(x -> x + 6 < :n &
x + 2 C :ludics &
x + 6 C :ludics).map(x -> (x, x + 2, x + 6))
print("\nThere are #. triplets less than #.:\n #.".format(triplets.len, n, triplets)) |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #Forth | Forth | \ magic eight ball Rosetta Code
INCLUDE RANDOM.FS
DECIMAL
: CASE: ( -- -7) CREATE ;
: ;CASE ( n -- ) DOES> SWAP CELLS + @ EXECUTE ;
: VECTORS 0 DO , LOOP ;
:NONAME ." It is certain" ;
:NONAME ." It is decidedly so" ;
:NONAME ." Without a doubt" ;
:NONAME ." Yes, definitely" ;
:NONAME ." You may rely on it" ;
:NONAME ." As I see it, yes." ;
:NONAME ." Most likely" ;
:NONAME ." Outlook good" ;
:NONAME ." Signs point to yes." ;
:NONAME ." Yes." ;
:NONAME ." Reply hazy, try again" ;
:NONAME ." Ask again later" ;
:NONAME ." Better not tell you now" ;
:NONAME ." Cannot predict now" ;
:NONAME ." Concentrate and ask again" ;
:NONAME ." Don't bet on it" ;
:NONAME ." My reply is no" ;
:NONAME ." My sources say no" ;
:NONAME ." Outlook not so good" ;
:NONAME ." Very doubtful" ;
CASE: MAGIC8BALL 20 VECTORS ;CASE
: GO
CR ." Please enter your question or a blank line to quit."
BEGIN CR ." ? :" PAD 80 ACCEPT 0>
WHILE CR 19 RANDOM MAGIC8BALL CR
REPEAT ; |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #Fortran | Fortran | PROGRAM EIGHT_BALL
CHARACTER(LEN=100) :: RESPONSE
CHARACTER(LEN=100) :: QUESTION
CHARACTER(LEN=100), DIMENSION(20) :: RESPONSES
REAL :: R
CALL RANDOM_SEED()
RESPONSES(1) = "It is certain"
RESPONSES(2) = "It is decidedly so"
RESPONSES(3) = "Without a doubt"
RESPONSES(4) = "Yes, definitely"
RESPONSES(5) = "You may rely on it"
RESPONSES(6) = "As I see it, yes"
RESPONSES(7) = "Most likely"
RESPONSES(8) = "Outlook good"
RESPONSES(9) = "Signs point to yes"
RESPONSES(10) = "Yes"
RESPONSES(11) = "Reply hazy, try again"
RESPONSES(12) = "Ask again later"
RESPONSES(13) = "Better not tell you now"
RESPONSES(14) = "Cannot predict now"
RESPONSES(15) = "Concentrate and ask again"
RESPONSES(16) = "Don't bet on it"
RESPONSES(17) = "My reply is no"
RESPONSES(18) = "My sources say no"
RESPONSES(19) = "Outlook not so good"
RESPONSES(20) = "Very doubtful"
WRITE(*,*) "Welcome to 8 Ball! Ask a question to find the answers"
WRITE(*,*) "you seek, type either 'quit' or 'q' to exit", NEW_LINE('A')
DO WHILE(.TRUE.)
PRINT*, "Ask your question: "
READ(*,*) QUESTION
IF(QUESTION == "q" .OR. QUESTION == "quit") THEN
CALL EXIT(0)
ENDIF
CALL RANDOM_NUMBER(R)
PRINT*, "Response: ", TRIM(RESPONSES(FLOOR(R*20))), NEW_LINE('A')
ENDDO
END PROGRAM EIGHT_BALL |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Raku | Raku | c = ((int (*) (int, int))buf)(a, b); |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Rust | Rust | extern crate libc;
#[cfg(all(
target_os = "linux",
any(target_pointer_width = "32", target_pointer_width = "64")
))]
fn main() {
use std::mem;
use std::ptr;
let page_size: usize = 4096;
let (bytes, size): (Vec<u8>, usize) = if cfg!(target_pointer_width = "32") {
(
vec![0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3],
9,
)
} else {
(vec![0x48, 0x89, 0xf8, 0x48, 0x01, 0xf0, 0xc3], 7)
};
let f: fn(u8, u8) -> u8 = unsafe {
let mut page: *mut libc::c_void = ptr::null_mut();
libc::posix_memalign(&mut page, page_size, size);
libc::mprotect(
page,
size,
libc::PROT_EXEC | libc::PROT_READ | libc::PROT_WRITE,
);
let contents: *mut u8 = page as *mut u8;
ptr::copy(bytes.as_ptr(), contents, 9);
mem::transmute(contents)
};
let return_value = f(7, 12);
println!("Returned value: {}", return_value);
assert_eq!(return_value, 19);
}
#[cfg(any(
not(target_os = "linux"),
not(any(target_pointer_width = "32", target_pointer_width = "64"))
))]
fn main() {
println!("Not supported on this platform.");
}
|
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Scala | Scala | import org.rosettacode.ArithmeticComplex._
import java.awt.Color
object Mandelbrot
{
def generate(width:Int =600, height:Int =400)={
val bm=new RgbBitmap(width, height)
val maxIter=1000
val xMin = -2.0
val xMax = 1.0
val yMin = -1.0
val yMax = 1.0
val cx=(xMax-xMin)/width
val cy=(yMax-yMin)/height
for(y <- 0 until bm.height; x <- 0 until bm.width){
val c=Complex(xMin+x*cx, yMin+y*cy)
val iter=itMandel(c, maxIter, 4)
bm.setPixel(x, y, getColor(iter, maxIter))
}
bm
}
def itMandel(c:Complex, imax:Int, bailout:Int):Int={
var z=Complex()
for(i <- 0 until imax){
z=z*z+c;
if(z.abs > bailout) return i
}
imax;
}
def getColor(iter:Int, max:Int):Color={
if (iter==max) return Color.BLACK
var c=3*math.log(iter)/math.log(max-1.0)
if(c<1) new Color((255*c).toInt, 0, 0)
else if(c<2) new Color(255, (255*(c-1)).toInt, 0)
else new Color(255, 255, (255*(c-2)).toInt)
}
} |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #VBA | VBA | Function matrix_multiplication(a As Variant, b As Variant) As Variant
matrix_multiplication = WorksheetFunction.MMult(a, b)
End Function |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #360_Assembly | 360 Assembly | * Ludic numbers 23/04/2016
LUDICN CSECT
USING LUDICN,R15 set base register
LH R9,NMAX r9=nmax
SRA R9,1 r9=nmax/2
LA R6,2 i=2
LOOPI1 CR R6,R9 do i=2 to nmax/2
BH ELOOPI1
LA R1,LUDIC-1(R6) @ludic(i)
CLI 0(R1),X'01' if ludic(i)
BNE ELOOPJ1
SR R8,R8 n=0
LA R7,1(R6) j=i+1
LOOPJ1 CH R7,NMAX do j=i+1 to nmax
BH ELOOPJ1
LA R1,LUDIC-1(R7) @ludic(j)
CLI 0(R1),X'01' if ludic(j)
BNE NOTJ1
LA R8,1(R8) n=n+1
NOTJ1 CR R8,R6 if n=i
BNE NDIFI
LA R1,LUDIC-1(R7) @ludic(j)
MVI 0(R1),X'00' ludic(j)=false
SR R8,R8 n=0
NDIFI LA R7,1(R7) j=j+1
B LOOPJ1
ELOOPJ1 LA R6,1(R6) i=i+1
B LOOPI1
ELOOPI1 XPRNT =C'First 25 ludic numbers:',23
LA R10,BUF @buf=0
SR R8,R8 n=0
LA R6,1 i=1
LOOPI2 CH R6,NMAX do i=1 to nmax
BH ELOOPI2
LA R1,LUDIC-1(R6) @ludic(i)
CLI 0(R1),X'01' if ludic(i)
BNE NOTI2
XDECO R6,XDEC i
MVC 0(4,R10),XDEC+8 output i
LA R10,4(R10) @buf=@buf+4
LA R8,1(R8) n=n+1
LR R2,R8 n
SRDA R2,32
D R2,=F'5' r2=mod(n,5)
LTR R2,R2 if mod(n,5)=0
BNZ NOTI2
XPRNT BUF,20
LA R10,BUF @buf=0
NOTI2 EQU *
CH R8,=H'25' if n=25
BE ELOOPI2
LA R6,1(R6) i=i+1
B LOOPI2
ELOOPI2 MVC BUF(25),=C'Ludic numbers below 1000:'
SR R8,R8 n=0
LA R6,1 i=1
LOOPI3 CH R6,=H'999' do i=1 to 999
BH ELOOPI3
LA R1,LUDIC-1(R6) @ludic(i)
CLI 0(R1),X'01' if ludic(i)
BNE NOTI3
LA R8,1(R8) n=n+1
NOTI3 LA R6,1(R6) i=i+1
B LOOPI3
ELOOPI3 XDECO R8,XDEC edit n
MVC BUF+25(6),XDEC+6 output n
XPRNT BUF,31 print buffer
MVC BUF(80),=CL80'Ludic numbers 2000 to 2005:'
LA R10,BUF+28 @buf=28
SR R8,R8 n=0
LA R6,1 i=1
LOOPI4 CH R6,NMAX do i=1 to nmax
BH ELOOPI4
LA R1,LUDIC-1(R6) @ludic(i)
CLI 0(R1),X'01' if ludic(i)
BNE NOTI4
LA R8,1(R8) n=n+1
CH R8,=H'2000' if n>=2000
BL NOTI4
XDECO R6,XDEC edit i
MVC 0(6,R10),XDEC+6 output i
LA R10,6(R10) @buf=@buf+6
CH R8,=H'2005' if n=2005
BE ELOOPI4
NOTI4 LA R6,1(R6) i=i+1
B LOOPI4
ELOOPI4 XPRNT BUF,80 print buffer
XPRNT =C'Ludic triplets below 250:',25
LA R6,1 i=1
LOOPI5 CH R6,=H'243' do i=1 to 243
BH ELOOPI5
LA R1,LUDIC-1(R6) @ludic(i)
CLI 0(R1),X'01' if ludic(i)
BNE ITERI5
LA R1,LUDIC+1(R6) @ludic(i+2)
CLI 0(R1),X'01' if ludic(i+2)
BNE ITERI5
LA R1,LUDIC+5(R6) @ludic(i+6)
CLI 0(R1),X'01' if ludic(i+6)
BNE ITERI5
MVC BUF+0(1),=C'[' [
XDECO R6,XDEC edit i
MVC BUF+1(4),XDEC+8 output i
LA R2,2(R6) i+2
XDECO R2,XDEC edit i+2
MVC BUF+5(4),XDEC+8 output i+2
LA R2,6(R6) i+6
XDECO R2,XDEC edit i+6
MVC BUF+9(4),XDEC+8 output i+6
MVC BUF+13(1),=C']' ]
XPRNT BUF,14 print buffer
ITERI5 LA R6,1(R6) i=i+1
B LOOPI5
ELOOPI5 XR R15,R15 set return code
BR R14 return to caller
LTORG
BUF DS CL80 buffer
XDEC DS CL12 decimal editor
NMAX DC H'25000' nmax
LUDIC DC 25000X'01' ludic(nmax)=true
YREGS
END LUDICN |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #Go | Go | package main
import (
"bufio"
"bytes"
"fmt"
"log"
"math/rand"
"os"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
answers := [...]string{
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful",
}
const prompt = "\n? : "
fmt.Print("Please enter your question or a blank line to quit.\n" + prompt)
sc := bufio.NewScanner(os.Stdin)
for sc.Scan() {
question := sc.Bytes()
question = bytes.TrimSpace(question)
if len(question) == 0 {
break
}
answer := answers[rand.Intn(len(answers))]
fmt.Printf("\n%s\n"+prompt, answer)
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
} |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Scala | Scala | !ExternalBytes class methods!
mapExecutableBytes:size
%{
# include <sys/mman.h>
void *mem;
OBJ retVal;
int nBytes = __intVal(size);
mem = mmap(nil, nBytes, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0);
if (mem != MAP_FAILED) {
RETURN( __MKEXTERNALBYTES_N(mem, nBytes));
}
%}.
self primitiveFailed
! ! |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Smalltalk | Smalltalk | !ExternalBytes class methods!
mapExecutableBytes:size
%{
# include <sys/mman.h>
void *mem;
OBJ retVal;
int nBytes = __intVal(size);
mem = mmap(nil, nBytes, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0);
if (mem != MAP_FAILED) {
RETURN( __MKEXTERNALBYTES_N(mem, nBytes));
}
%}.
self primitiveFailed
! ! |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Scheme | Scheme | (define x-centre -0.5)
(define y-centre 0.0)
(define width 4.0)
(define i-max 800)
(define j-max 600)
(define n 100)
(define r-max 2.0)
(define file "out.pgm")
(define colour-max 255)
(define pixel-size (/ width i-max))
(define x-offset (- x-centre (* 0.5 pixel-size (+ i-max 1))))
(define y-offset (+ y-centre (* 0.5 pixel-size (+ j-max 1))))
(define (inside? z)
(define (*inside? z-0 z n)
(and (< (magnitude z) r-max)
(or (= n 0)
(*inside? z-0 (+ (* z z) z-0) (- n 1)))))
(*inside? z 0 n))
(define (boolean->integer b)
(if b colour-max 0))
(define (pixel i j)
(boolean->integer
(inside?
(make-rectangular (+ x-offset (* pixel-size i))
(- y-offset (* pixel-size j))))))
(define (plot)
(with-output-to-file file
(lambda ()
(begin (display "P2") (newline)
(display i-max) (newline)
(display j-max) (newline)
(display colour-max) (newline)
(do ((j 1 (+ j 1))) ((> j j-max))
(do ((i 1 (+ i 1))) ((> i i-max))
(begin (display (pixel i j)) (newline))))))))
(plot) |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #VBScript | VBScript |
Dim matrix1(2,2)
matrix1(0,0) = 3 : matrix1(0,1) = 7 : matrix1(0,2) = 4
matrix1(1,0) = 5 : matrix1(1,1) = -2 : matrix1(1,2) = 9
matrix1(2,0) = 8 : matrix1(2,1) = -6 : matrix1(2,2) = -5
Dim matrix2(2,2)
matrix2(0,0) = 9 : matrix2(0,1) = 2 : matrix2(0,2) = 1
matrix2(1,0) = -7 : matrix2(1,1) = 3 : matrix2(1,2) = -10
matrix2(2,0) = 4 : matrix2(2,1) = 5 : matrix2(2,2) = -6
Call multiply_matrix(matrix1,matrix2)
Sub multiply_matrix(arr1,arr2)
For i = 0 To UBound(arr1)
For j = 0 To 2
WScript.StdOut.Write (arr1(i,j) * arr2(i,j)) & vbTab
Next
WScript.StdOut.WriteLine
Next
End Sub
|
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #ABAP | ABAP | CLASS lcl_ludic DEFINITION CREATE PUBLIC.
PUBLIC SECTION.
TYPES: t_ludics TYPE SORTED TABLE OF i WITH UNIQUE KEY table_line.
TYPES: BEGIN OF t_triplet,
i1 TYPE i,
i2 TYPE i,
i3 TYPE i,
END OF t_triplet.
TYPES: t_triplets TYPE STANDARD TABLE OF t_triplet WITH EMPTY KEY.
CLASS-METHODS:
ludic_up_to
IMPORTING i_int TYPE i
RETURNING VALUE(r_ludics) TYPE t_ludics,
get_triplets
IMPORTING i_ludics TYPE t_ludics
RETURNING VALUE(r_triplets) TYPE t_triplets.
"RETURNING parameters (CallByValue) only used for readability of the demo
"in "Real Life" you should use EXPORTING (CallByRef) for tables
ENDCLASS.
cl_demo_output=>begin_section( 'First 25 Ludics' ).
cl_demo_output=>write( lcl_ludic=>ludic_up_to( 110 ) ).
cl_demo_output=>begin_section( 'Ludics up to 1000' ).
cl_demo_output=>write( lines( lcl_ludic=>ludic_up_to( 1000 ) ) ).
cl_demo_output=>begin_section( '2000th - 2005th Ludics' ).
DATA(ludics) = lcl_ludic=>ludic_up_to( 22000 ).
cl_demo_output=>write( VALUE lcl_ludic=>t_ludics( FOR i = 2000 WHILE i <= 2005 ( ludics[ i ] ) ) ).
cl_demo_output=>begin_section( 'Triplets up to 250' ).
cl_demo_output=>write( lcl_ludic=>get_triplets( lcl_ludic=>ludic_up_to( 250 ) ) ).
cl_demo_output=>display( ).
CLASS lcl_ludic IMPLEMENTATION.
METHOD ludic_up_to.
r_ludics = VALUE #( FOR i = 2 WHILE i <= i_int ( i ) ).
DATA(cursor) = 0.
WHILE cursor < lines( r_ludics ).
cursor = cursor + 1.
DATA(this_ludic) = r_ludics[ cursor ].
DATA(remove_cursor) = cursor + this_ludic.
WHILE remove_cursor <= lines( r_ludics ).
DELETE r_ludics INDEX remove_cursor.
remove_cursor = remove_cursor + this_ludic - 1.
ENDWHILE.
ENDWHILE.
INSERT 1 INTO TABLE r_ludics. "add one as the first Ludic number (per definition)
ENDMETHOD.
METHOD get_triplets.
DATA(i) = 0.
WHILE i < lines( i_ludics ) - 2.
i = i + 1.
DATA(this_ludic) = i_ludics[ i ].
IF line_exists( i_ludics[ table_line = this_ludic + 2 ] )
AND line_exists( i_ludics[ table_line = this_ludic + 6 ] ).
r_triplets = VALUE #(
BASE r_triplets
( i1 = i_ludics[ table_line = this_ludic ]
i2 = i_ludics[ table_line = this_ludic + 2 ]
i3 = i_ludics[ table_line = this_ludic + 6 ]
)
).
ENDIF.
ENDWHILE.
ENDMETHOD.
ENDCLASS. |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #GW-BASIC | GW-BASIC | 0 DATA "It is certain.", "It is decidedly so."
20 DATA "Without a doubt.", "Yes - definitely."
30 DATA "You may rely on it.", "As I see it, yes."
40 DATA "Most likely.", "Outlook good."
50 DATA "Yes.", "Signs point to yes."
60 DATA "Reply hazy, try again.", "Ask again later."
70 DATA "Better not tell you now.", "Cannot predict now."
80 DATA "Concentrate and ask again.", "Don't count on it."
90 DATA "My reply is no.", "My sources say no."
100 DATA "Outlook not so good.", "Very doubtful."
110 DIM M8BALL$(20)
120 FOR I=0 TO 19
130 READ M8BALL$(I)
140 NEXT I
150 RANDOMIZE TIMER
160 INPUT "What would you like to know? ", Q$
170 PRINT M8BALL$(INT(RND*20))
180 END |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Swift | Swift | import Foundation
typealias TwoIntsOneInt = @convention(c) (Int, Int) -> Int
let code = [
144, // Align
144,
106, 12, // Prepare stack
184, 7, 0, 0, 0,
72, 193, 224, 32,
80,
139, 68, 36, 4, 3, 68, 36, 8, // Rosetta task code
76, 137, 227, // Get result
137, 195,
72, 193, 227, 4,
128, 203, 2,
72, 131, 196, 16, // Clean up stack
195, // Return
] as [UInt8]
func fudge(x: Int, y: Int) -> Int {
let buf = mmap(nil, code.count, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0)
memcpy(buf, code, code.count)
let fun = unsafeBitCast(buf, to: TwoIntsOneInt.self)
let ret = fun(x, y)
munmap(buf, code.count)
return ret
}
print(fudge(x: 7, y: 12))
|
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Tcl | Tcl | package require critcl
critcl::ccode {
#include <sys/mman.h>
}
# Define a command using C. The C is embedded in Tcl, and will be
# built into a shared library at runtime. Note that Tcl does not
# provide a native way of doing this sort of thing; this thunk is
# mandatory.
critcl::cproc runMachineCode {Tcl_Obj* codeObj int a int b} int {
int size, result;
unsigned char *code = Tcl_GetByteArrayFromObj(codeObj, &size);
void *buf;
/* copy code to executable buffer */
buf = mmap(0, (size_t) size, PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANON, -1, 0);
memcpy(buf, code, (size_t) size);
/* run code */
result = ((int (*) (int, int)) buf)(a, b);
/* dispose buffer */
munmap(buf, (size_t) size);
return result;
}
# But now we have our thunk, we can execute arbitrary binary blobs
set code [binary format c* {0x8B 0x44 0x24 0x4 0x3 0x44 0x24 0x8 0xC3}]
puts [runMachineCode $code 7 12] |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Scratch | Scratch | $ include "seed7_05.s7i";
include "float.s7i";
include "complex.s7i";
include "draw.s7i";
include "keybd.s7i";
# Display the Mandelbrot set, that are points z[0] in the complex plane
# for which the sequence z[n+1] := z[n] ** 2 + z[0] (n >= 0) is bounded.
# Since this program is computing intensive it should be compiled with
# hi comp -O2 mandelbr
const integer: pix is 200;
const integer: max_iter is 256;
var array color: colorTable is max_iter times black;
const func integer: iterate (in complex: z0) is func
result
var integer: iter is 1;
local
var complex: z is complex.value;
begin
z := z0;
while sqrAbs(z) < 4.0 and # not diverged
iter < max_iter do # not converged
z *:= z;
z +:= z0;
incr(iter);
end while;
end func;
const proc: displayMandelbrotSet (in complex: center, in float: zoom) is func
local
var integer: x is 0;
var integer: y is 0;
var complex: z0 is complex.value;
begin
for x range -pix to pix do
for y range -pix to pix do
z0 := center + complex(flt(x) * zoom, flt(y) * zoom);
point(x + pix, y + pix, colorTable[iterate(z0)]);
end for;
end for;
end func;
const proc: main is func
local
const integer: num_pix is 2 * pix + 1;
var integer: col is 0;
begin
screen(num_pix, num_pix);
clear(curr_win, black);
KEYBOARD := GRAPH_KEYBOARD;
for col range 1 to pred(max_iter) do
colorTable[col] := color(65535 - (col * 5003) mod 65535,
(col * 257) mod 65535,
(col * 2609) mod 65535);
end for;
displayMandelbrotSet(complex(-0.75, 0.0), 1.3 / flt(pix));
DRAW_FLUSH;
readln(KEYBOARD);
end func;
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Visual_FoxPro | Visual FoxPro |
LOCAL ARRAY a[4,2], b[2,3], c[4,3]
CLOSE DATABASES ALL
*!* The arrays could be created directly but I prefer to do this:
CREATE CURSOR mat1 (c1 I, c2 I)
CREATE CURSOR mat2 (c1 I, c2 I, c3 I)
*!* Since matrix multiplication of integer arrays
*!* involves only multiplication and addition,
*!* the result will contain integers
CREATE CURSOR result (c1 I, c2 I, c3 I)
INSERT INTO mat1 VALUES (1, 2)
INSERT INTO mat1 VALUES (3, 4)
INSERT INTO mat1 VALUES (5, 6)
INSERT INTO mat1 VALUES (7, 8)
SELECT * FROM mat1 INTO ARRAY a
INSERT INTO mat2 VALUES (1, 2, 3)
INSERT INTO mat2 VALUES (4, 5, 6)
SELECT * FROM mat2 INTO ARRAY b
STORE 0 TO c
MatMult(@a,@b,@c)
SELECT result
APPEND FROM ARRAY c
BROWSE
PROCEDURE MatMult(aa, bb, cc)
LOCAL n As Integer, m As Integer, p As Integer, i As Integer, j As Integer, k As Integer
IF ALEN(aa,2) = ALEN(bb,1)
n = ALEN(aa,2)
m = ALEN(aa,1)
p = ALEN(bb,2)
FOR i = 1 TO m
FOR j = 1 TO p
FOR k = 1 TO n
cc[i,j] = cc[i,j] + aa[i,k]*bb[k,j]
ENDFOR
ENDFOR
ENDFOR
ELSE
? "Invalid dimensions"
ENDIF
ENDPROC
|
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #Action.21 | Action! | DEFINE NOTLUDIC="0"
DEFINE LUDIC="1"
DEFINE UNKNOWN="2"
PROC LudicSieve(BYTE ARRAY a INT count)
INT i,j,k
SetBlock(a,count,UNKNOWN)
a(0)=NOTLUDIC
a(1)=LUDIC
i=2
WHILE i<count
DO
IF a(i)=UNKNOWN THEN
a(i)=LUDIC
j=i k=0
WHILE j<count
DO
IF a(j)=UNKNOWN THEN
k==+1
IF k=i THEN
a(j)=NOTLUDIC
k=0
FI
FI
j==+1
OD
FI
i==+1
Poke(77,0) ;turn off the attract mode
OD
RETURN
PROC PrintLudicNumbers(BYTE ARRAY a INT count,first,last)
INT i,j
i=1 j=0
WHILE i<count AND j<=last
DO
IF a(i)=LUDIC THEN
IF j>=first THEN
PrintI(i) Put(32)
FI
j==+1
FI
i==+1
OD
PutE() PutE()
RETURN
INT FUNC CountLudicNumbers(BYTE ARRAY a INT max)
INT i,res
res=0
FOR i=1 TO max
DO
IF a(i)=LUDIC THEN
res==+1
FI
OD
RETURN (res)
PROC PrintLudicTriplets(BYTE ARRAY a INT max)
INT i,j
j=0
FOR i=0 TO max-6
DO
IF a(i)=LUDIC AND a(i+2)=LUDIC AND a(i+6)=LUDIC THEN
j==+1
PrintF("%I. %I-%I-%I%E",j,i,i+2,i+6)
FI
OD
RETURN
PROC Main()
DEFINE COUNT="22000"
BYTE ARRAY lud(COUNT+1)
INT i,n
PrintE("Please wait...")
LudicSieve(lud,COUNT+1)
Put(125) PutE() ;clear the screen
PrintE("First 25 ludic numbers:")
PrintLudicNumbers(lud,COUNT+1,0,24)
n=CountLudicNumbers(lud,1000)
PrintF("There are %I ludic numbers <= 1000%E%E",n)
PrintE("2000'th..2005'th ludic numbers:")
PrintLudicNumbers(lud,COUNT+1,1999,2004)
PrintE("Ludic triplets below 250")
PrintLudicTriplets(lud,249)
RETURN |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #Haskell | Haskell | import System.Random (getStdRandom, randomR)
import Control.Monad (forever)
answers :: [String]
answers =
[ "It is certain"
, "It is decidedly so"
, "Without a doubt"
, "Yes, definitely"
, "You may rely on it"
, "As I see it, yes"
, "Most likely"
, "Outlook good"
, "Signs point to yes"
, "Yes"
, "Reply hazy, try again"
, "Ask again later"
, "Better not tell you now"
, "Cannot predict now"
, "Concentrate and ask again"
, "Don't bet on it"
, "My reply is no"
, "My sources say no"
, "Outlook not so good"
, "Very doubtful"]
main :: IO ()
main = do
putStrLn "Hello. The Magic 8 Ball knows all. Type your question."
forever $ do
getLine
n <- getStdRandom (randomR (0, pred $ length answers))
putStrLn $ answers !! n |
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #Wren | Wren | /* machine_code.wren */
class C {
// pass the machine code in string form to the host
foreign static runMachineCode(s, a, b)
}
var a = 7
var b = 12
// x64 opcodes for this task
var m = [
0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,
0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,
0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,
0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3
]
var s = m.map { |byte| String.fromByte(byte) }.join()
System.print("%(a) + %(b) = %(C.runMachineCode(s, a, b))") |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "complex.s7i";
include "draw.s7i";
include "keybd.s7i";
# Display the Mandelbrot set, that are points z[0] in the complex plane
# for which the sequence z[n+1] := z[n] ** 2 + z[0] (n >= 0) is bounded.
# Since this program is computing intensive it should be compiled with
# hi comp -O2 mandelbr
const integer: pix is 200;
const integer: max_iter is 256;
var array color: colorTable is max_iter times black;
const func integer: iterate (in complex: z0) is func
result
var integer: iter is 1;
local
var complex: z is complex.value;
begin
z := z0;
while sqrAbs(z) < 4.0 and # not diverged
iter < max_iter do # not converged
z *:= z;
z +:= z0;
incr(iter);
end while;
end func;
const proc: displayMandelbrotSet (in complex: center, in float: zoom) is func
local
var integer: x is 0;
var integer: y is 0;
var complex: z0 is complex.value;
begin
for x range -pix to pix do
for y range -pix to pix do
z0 := center + complex(flt(x) * zoom, flt(y) * zoom);
point(x + pix, y + pix, colorTable[iterate(z0)]);
end for;
end for;
end func;
const proc: main is func
local
const integer: num_pix is 2 * pix + 1;
var integer: col is 0;
begin
screen(num_pix, num_pix);
clear(curr_win, black);
KEYBOARD := GRAPH_KEYBOARD;
for col range 1 to pred(max_iter) do
colorTable[col] := color(65535 - (col * 5003) mod 65535,
(col * 257) mod 65535,
(col * 2609) mod 65535);
end for;
displayMandelbrotSet(complex(-0.75, 0.0), 1.3 / flt(pix));
DRAW_FLUSH;
readln(KEYBOARD);
end func;
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Wren | Wren | import "/matrix" for Matrix
import "/fmt" for Fmt
var a = Matrix.new([
[1, 2],
[3, 4],
[5, 6],
[7, 8]
])
var b = Matrix.new([
[1, 2, 3],
[4, 5, 6]
])
System.print("Matrix A:\n")
Fmt.mprint(a, 2, 0)
System.print("\nMatrix B:\n")
Fmt.mprint(b, 2, 0)
System.print("\nMatrix A x B:\n")
Fmt.mprint(a * b, 3, 0) |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
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
| #11l | 11l | V template = ‘<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.’
F madlibs(template)
print("The story template is:\n"template)
V fields = sorted(Array(Set(re:‘<[^>]+>’.find_strings(template))))
V values = input("\nInput a comma-separated list of words to replace the following items\n #.: ".format(fields.join(‘,’))).split(‘,’)
V story = template
L(f, v) zip(fields, values)
story = story.replace(f, v)
print("\nThe story becomes:\n\n"story)
madlibs(template) |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #Ada | Ada | with Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Ludic_Numbers is
package Lucid_Lists is
new Ada.Containers.Vectors (Positive, Natural);
use Lucid_Lists;
List : Vector;
procedure Fill is
use type Ada.Containers.Count_Type;
Vec : Vector;
Lucid : Natural;
Index : Positive;
begin
Append (List, 1);
for I in 2 .. 22_000 loop
Append (Vec, I);
end loop;
loop
Lucid := First_Element (Vec);
Append (List, Lucid);
Index := First_Index (Vec);
loop
Delete (Vec, Index);
Index := Index + Lucid - 1;
exit when Index > Last_Index (Vec);
end loop;
exit when Length (Vec) <= 1;
end loop;
end Fill;
procedure Put_Lucid (First, Last : in Natural) is
use Ada.Text_IO;
begin
Put_Line ("Lucid numbers " & First'Image & " to " & Last'Image & ":");
for I in First .. Last loop
Put (Natural'(List (I))'Image);
end loop;
New_Line;
end Put_Lucid;
procedure Count_Lucid (Below : in Natural) is
Count : Natural := 0;
begin
for Lucid of List loop
if Lucid <= Below then
Count := Count + 1;
end if;
end loop;
Ada.Text_IO.Put_Line ("There are " & Count'Image & " lucid numbers <=" & Below'Image);
end Count_Lucid;
procedure Find_Triplets (Limit : in Natural) is
function Is_Lucid (Value : in Natural) return Boolean is
begin
for X in 1 .. Limit loop
if List (X) = Value then
return True;
end if;
end loop;
return False;
end Is_Lucid;
use Ada.Text_IO;
Index : Natural;
Lucid : Natural;
begin
Put_Line ("All triplets of lucid numbers <" & Limit'Image);
Index := First_Index (List);
while List (Index) < Limit loop
Lucid := List (Index);
if Is_Lucid (Lucid + 2) and Is_Lucid (Lucid + 6) then
Put ("(");
Put (Lucid'Image);
Put (Natural'(Lucid + 2)'Image);
Put (Natural'(Lucid + 6)'Image);
Put_Line (")");
end if;
Index := Index + 1;
end loop;
end Find_Triplets;
begin
Fill;
Put_Lucid (First => 1,
Last => 25);
Count_Lucid (Below => 1000);
Put_Lucid (First => 2000,
Last => 2005);
Find_Triplets (Limit => 250);
end Ludic_Numbers; |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #J | J |
NB. translated from awk
prompt=: [: 1!:1 [: 1: echo
ANSWERS=: [;._2'It is certain"It is decidedly so"Without a doubt"Yes, definitely"You may rely on it"As I see it, yes"Most likely"Outlook good"Signs point to yes"Yes"Reply hazy, try again"Ask again later"Better not tell you now"Cannot predict now"Concentrate and ask again"Don''t bet on it"My reply is no"My sources say no"Outlook not so good"Very doubtful"'
eight_ball=: ANSWERS&$: :(dyad define)
while. 0 < # prompt 'Please enter your question or a blank line to quit.' do.
echo ({~ ?@:#) x
end.
)
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #Java | Java |
import java.util.Random;
import java.util.Scanner;
public class MagicEightBall {
public static void main(String[] args) {
new MagicEightBall().run();
}
private static String[] ANSWERS = new String[] {"It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.",
"You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",
"Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
"Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful. "};
public void run() {
Random random = new Random();
System.out.printf("Hello. The Magic 8 Ball knows all. Type your question.%n%n");
try ( Scanner in = new Scanner(System.in); ) {
System.out.printf("? ");
while ( (in.nextLine()).length() > 0 ) {
System.out.printf("8 Ball Response: %s%n", ANSWERS[random.nextInt(ANSWERS.length)]);
System.out.printf("? ");
}
}
System.out.printf("%n8 Ball Done. Bye.");
}
}
|
http://rosettacode.org/wiki/Machine_code | Machine code | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
Task
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
Poke the necessary opcodes into a memory location.
Provide a means to pass two values to the machine code.
Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| #X86-64_Assembly | X86-64 Assembly |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Linux Build:
;; $ uasm -elf64 mexec.asm
;; $ gcc -o mexec mexec.o -no-pie
;; With MUSL libc
;; $ musl-gcc -o mexec mexec.o -e main -nostartfiles -no-pie
;;
;; Windows Build:
;; $ uasm64 -win64 mexec.asm
;; $ link /machine:x64 /subsystem:console /release mexec.obj
;; kernel32.lib msvcrt.lib
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
option casemap:none
option literals:on
WIN64 equ 1
LIN64 equ 3
ifndef __MEMEXEC_CLASS__
__MEMEXEC_CLASS__ equ 1
if @Platform eq WIN64
option dllimport:<kernel32>
HeapAlloc proto fd:qword, flgs:dword, hlen:qword
HeapFree proto fd:qword, flgs:dword, lpmem:qword
GetProcessHeap proto
ExitProcess proto uexit:word
option dllimport:<msvcrt>
printf proto fmt:qword, args:VARARG
memcpy proto d:qword, s:qword, mlen:qword
option dllimport:none
exit equ ExitProcess
elseif @Platform eq LIN64
malloc proto SYSTEMV len:qword
free proto SYSTEMV m:qword
printf proto SYSTEMV fmt:qword, args:VARARG
mprotect proto SYSTEMV m:qword, s:qword, flgs:dword
memcpy proto SYSTEMV d:qword, s:qword, mlen:qword
exit proto SYSTEMV uexit:word
PROT_READ equ 01h
PROT_WRITE equ 02h
PROT_EXEC equ 04h
PROT_NONE equ 00h
PROT_ALL equ PROT_READ + PROT_WRITE + PROT_EXEC
endif
CLASS memexec
CMETHOD run
ENDMETHODS
buff db 048h, 089h, 0F8h ;; mov rax, rdi
db 048h, 001h, 0F0h ;; add rax, rsi
db 0C3h ;; ret
mem dq ? ;; Memory address
mlen dq 0 ;; Memory size allocated?
ENDCLASS
pmemexec typedef ptr memexec
METHOD memexec, Init, <VOIDARG>, <uses rcx>
local tmp:qword
mov rbx, thisPtr
assume rbx:ptr memexec
lea rdx, [rbx].buff
invoke printf, CSTR("[mexec->Init] - bytecode addr: 0x%X",10), rdx
mov tmp, rdx
mov [rbx].mlen, sizeof(tmp)
invoke printf, CSTR("[mexec->Init] - bytecode len: %i",10), [rbx].mlen
;; In Built memory allocator, used by the Class extention
;; Uses either HeapAlloc for windows or malloc for everything else.
;; Which is why I didn't use mmap in the first place.
MEMALLOC([rbx].mlen)
.if rax == -1
invoke printf, CSTR("[exec->Init->Error] - Malloc failed with -1",10)
mov rax, rbx
ret
.endif
mov [rbx].mem, rax
invoke printf, CSTR("[mexec->Init] - [rbx].mem addr: 0x%X",10), [rbx].mem
;; Memory wont be executable by default from Malloc, So we make it
;; so with mprotect. Not sure about windows, Might need to use a VirtualProtect
;; call..
if @Platform eq LIN64
invoke mprotect, [rbx].mem, [rbx].mlen, PROT_ALL
.if rax == -1
invoke printf, CSTR("[exec]-Init->Error] - mprotect failed with -1",10)
mov rax, rbx
ret
.endif
endif
invoke printf, CSTR("[mexec->Init] Copying [rbx].buff bytecode to 0x%X",10), [rbx].mem
invoke memcpy, [rbx].mem, addr [rbx].buff, [rbx].mlen
.if rax == -1
invoke printf, CSTR("[mexec->Init->Error] - memcpy failed with -l",10)
mov rax, rbx
ret
.endif
mov rcx, [rbx].mem
mov rax, rbx
assume rbx:nothing
ret
ENDMETHOD
METHOD memexec, run, <VOIDARG>, <>, arg1:qword, arg2:qword
mov rbx, thisPtr
assume rbx:ptr memexec
mov rdi, arg1
mov rsi, arg2
call [rbx].mem
assume rbx:nothing
ret
ENDMETHOD
METHOD memexec, Destroy, <VOIDARG>, <>
mov rbx, thisPtr
assume rbx:ptr memexec
mov [rbx].mlen, 0
MEMFREE([rbx].mem)
assume rbx:nothing
ret
ENDMETHOD
endif ;; __MEMEXEC_CLASS__
.data
a1 dq 7
a2 dq 12
.code
main proc
local pmem:ptr memexec
mov pmem, _NEW(memexec)
pmem->run(a1,a2)
invoke printf, CSTR("[pmem->run(%i, %i)] - returned: %i",10), a1, a2, rax
_DELETE(pmem)
invoke exit, 0
ret
main endp
end
|
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #SenseTalk | SenseTalk | put 0 into oReal # Real origin
put 0 into oImag # Imaginary origin
put 0.5 into mag # Magnification
put oReal - .8 / mag into leftReal
put oImag + .5 / mag into topImag
put 1 / 200 / mag into inc
put [
(0,255,255), # aqua
(0,0,255), # blue
(255,0,255), # fuchsia
(128,128,128), # gray
(0,128,0), # green
(0,255,0), # lime
(128,0,0), # maroon
(0,0,128), # navy
(128,128,0), # olive
(128,0,128), # purple
(255,0,0), # red
(192,192,192), # silver
(0,128,128), # teal
(255,255,255), # white
(255,255,0) # yellow
] into colors
put "mandelbrot.ppm" into myFile
open file myFile for writing
write "P3" & return to file myFile # PPM file magic number
write "320 200" & return to file myFile # Width and height
write "255" & return to file myFile # Max value in color channels
put topImag into cImag
repeat with each item in 1 .. 200
put leftReal into cReal
repeat with each item in 1 .. 320
put 0 into zReal
put 0 into zImag
put 0 into count
put 0 into size
repeat at least once until size > 2 or count = 100
put zReal squared + zImag squared * -1 into newZreal
put zReal * zImag + zReal * zImag into newZimag
put newZreal + cReal into zReal
put newZimag + cImag into zImag
put sqrt(zReal squared + zImag squared) into size
add 1 to count
end repeat
if size > 2 then # Outside the set - colorize
put item count mod 15 + 1 of colors into color
write color joined by " " to file myFile
write return to file myFile
else # Inside the set - black
write "0 0 0" & return to file myFile
end if
add inc to cReal
end repeat
subtract inc from cImag
end repeat
close file myFile
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #XPL0 | XPL0 | proc Mat4x1Mul(M, V); \Multiply matrix M times column vector V
real M, \4x4 matrix [M] * [V] -> [V]
V; \column vector
real W(4); \working copy of column vector
int R; \row
[for R:= 0 to 4-1 do
W(R):= M(R,0)*V(0) + M(R,1)*V(1) + M(R,2)*V(2) + M(R,3)*V(3);
for R:= 0 to 4-1 do V(R):= W(R);
];
proc Mat4x4Mul(M, N); \Multiply matrix M times matrix N
real M, N; \4x4 matrices [M] * [N] -> [N]
real W(4,4); \working copy of matrix N
int C; \column
[for C:= 0 to 4-1 do
[W(0,C):= M(0,0)*N(0,C) + M(0,1)*N(1,C) + M(0,2)*N(2,C) + M(0,3)*N(3,C);
W(1,C):= M(1,0)*N(0,C) + M(1,1)*N(1,C) + M(1,2)*N(2,C) + M(1,3)*N(3,C);
W(2,C):= M(2,0)*N(0,C) + M(2,1)*N(1,C) + M(2,2)*N(2,C) + M(2,3)*N(3,C);
W(3,C):= M(3,0)*N(0,C) + M(3,1)*N(1,C) + M(3,2)*N(2,C) + M(3,3)*N(3,C);
];
for C:= 0 to 4-1 do
[N(0,C):= W(0,C);
N(1,C):= W(1,C);
N(2,C):= W(2,C);
N(3,C):= W(3,C);
];
]; |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
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
| #Ada | Ada | with Ada.Text_IO, Ada.Command_Line, String_Helper;
procedure Madlib is
use String_Helper;
Text: Vector := Get_Vector(Ada.Command_Line.Argument(1));
M, N: Natural;
begin
-- search for templates and modify the text accordingly
for I in Text.First_Index .. Text.Last_Index loop
loop
Search_Brackets(Text.Element(I), "<", ">", M, N);
exit when M=0; -- "M=0" means "not found"
Ada.Text_IO.Put_Line("Replacement for " & Text.Element(I)(M .. N) & "?");
declare
Old: String := Text.Element(I)(M .. N);
New_Word: String := Ada.Text_IO.Get_Line;
begin
for J in I .. Text.Last_Index loop
Text.Replace_Element(J, Replace(Text.Element(J), Old, New_Word));
end loop;
end;
end loop;
end loop;
-- write the text
for I in Text.First_Index .. Text.Last_Index loop
Ada.Text_IO.Put_Line(Text.Element(I));
end loop;
end Madlib; |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #ALGOL_68 | ALGOL 68 | # find some Ludic numbers #
# sieve the Ludic numbers up to 30 000 #
INT max number = 30 000;
[ 1 : max number ]INT candidates;
FOR n TO UPB candidates DO candidates[ n ] := n OD;
FOR n FROM 2 TO UPB candidates OVER 2 DO
IF candidates[ n ] /= 0 THEN
# have a ludic number #
INT number count := -1;
FOR remove pos FROM n TO UPB candidates DO
IF candidates[ remove pos ] /= 0 THEN
# have a number we haven't elminated yet #
number count +:= 1;
IF number count = n THEN
# this number should be removed #
candidates[ remove pos ] := 0;
number count := 0
FI
FI
OD
FI
OD;
# show some Ludic numbers and counts #
print( ( "Ludic numbers: " ) );
INT ludic count := 0;
FOR n TO UPB candidates DO
IF candidates[ n ] /= 0 THEN
# have a ludic number #
ludic count +:= 1;
IF ludic count < 26 THEN
# this is one of the first few Ludic numbers #
print( ( " ", whole( n, 0 ) ) );
IF ludic count = 25 THEN
print( ( " ...", newline ) )
FI
FI;
IF ludic count = 2000 THEN
print( ( "Ludic numbers 2000-2005: ", whole( n, 0 ) ) )
ELIF ludic count > 2000 AND ludic count < 2006 THEN
print( ( " ", whole( n, 0 ) ) );
IF ludic count = 2005 THEN
print( ( newline ) )
FI
FI
FI;
IF n = 1000 THEN
# count ludic numbers up to 1000 #
print( ( "There are ", whole( ludic count, 0 ), " Ludic numbers up to 1000", newline ) )
FI
OD;
# find the Ludic triplets below 250 #
print( ( "Ludic triplets below 250:", newline ) );
FOR n TO 250 - 6 DO
IF candidates[ n ] /= 0 AND candidates[ n + 2 ] /= 0 AND candidates[ n + 6 ] /= 0 THEN
# have a triplet #
print( ( " ", whole( n, -3 ), ", ", whole( n + 2, -3 ), ", ", whole( n + 6, -3 ), newline ) )
FI
OD |
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.