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/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Klingphix
|
Klingphix
|
:multiply * ;
2 3 multiply print { 6 }
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Kotlin
|
Kotlin
|
// One-liner
fun multiply(a: Int, b: Int) = a * b
// Proper function definition
fun multiplyProper(a: Int, b: Int): Int {
return a * b
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Teco
|
Teco
|
^AHello world!^A$$
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Erlang
|
Erlang
|
-module(fork).
-export([start/0]).
start() ->
erlang:spawn( fun() -> child() end ),
io:format("This is the original process~n").
child() ->
io:format("This is the new process~n").
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Factor
|
Factor
|
USING: unix unix.process ;
[ "Hello form child" print flush 0 _exit ] [ drop "Hi from parent" print flush ] with-fork
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Lambdatalk
|
Lambdatalk
|
{def multiply
{lambda {:a :b}
{* :a :b}}}
{multiply 3 4}
-> 12
could be written as a variadic function:
{def any_multiply
{lambda {:n} // thanks to variadicity of *
{* :n}}}
{any_multiply 1 2 3 4 5 6}
-> 720
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Tern
|
Tern
|
println("Hello world!");
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Fexl
|
Fexl
|
fork \pid
print "pid = ";print pid;nl;
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Furor
|
Furor
|
#g
."Kezd!\n"
§child fork sto childpid
@childpid wait
@childpid ."child pid ez volt: " printnl
end
child: ."Én a child vagyok!\n"
#d 3.14 printnl
2 sleep
end
{ „childpid” }
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#langur
|
langur
|
val .multiply = f(.x, .y) .x x .y
.multiply(3, 4)
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Lasso
|
Lasso
|
define multiply(a,b) => {
return #a * #b
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Terra
|
Terra
|
C = terralib.includec("stdio.h")
terra hello(argc : int, argv : &rawstring)
C.printf("Hello world!\n")
return 0
end
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#FreeBASIC
|
FreeBASIC
|
Function script(s As String) As String
Dim As String g = _
"Set WshShell = WScript.CreateObject(""WScript.Shell"")" + _
Chr(13,10) + "Return = WshShell.Run("""+s+" "",1,0)"
Return g
End Function
Function guardaArchivo(nombreArchivo As String, p As String) As String
Dim As Long n = Freefile
If Open (nombreArchivo For Binary Access Write As #n) = 0 Then
Put #n,,p
Close
Else
Print "No se puede guardar " + nombreArchivo : Sleep : End
End If
Return nombreArchivo
End Function
Sub ejecutaScript(nombreArchivo As String)
Shell "cscript.exe /Nologo " + nombreArchivo
End Sub
Var g = script("notepad.exe") '<< ejecuta este .exe (notepad como demo)
guardaArchivo("script.vbs",g)
ejecutaScript("script.vbs")
Dim As String s
Print "Hola"
Input "Teclee algo: ", s
Print s
Kill "script.vbs"
Sleep
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Go
|
Go
|
package main
import (
"fmt"
"os"
)
func main() {
fmt.Printf("PID: %v\n", os.Getpid())
if len(os.Args) < 2 {
fmt.Println("Done.")
return
}
cp, err := os.StartProcess(os.Args[0], nil,
&os.ProcAttr{Files: []*os.File{nil, os.Stdout}},
)
if err != nil {
fmt.Println(err)
}
// Child process running independently at this point.
// We have its PID and can print it.
fmt.Printf("Child's PID: %v\n", cp.Pid)
if _, err = cp.Wait(); err != nil {
fmt.Println(err)
}
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Latitude
|
Latitude
|
multiply := { $1 * $2. }.
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Terraform
|
Terraform
|
output "result" {
value = "Hello world!"
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Groovy
|
Groovy
|
println "BEFORE PROCESS"
Process p = Runtime.runtime.exec('''
C:/cygwin/bin/sh -c "
/usr/bin/date +'BEFORE LOOP: %T';
for i in 1 2 3 4 ; do
/usr/bin/sleep 1;
/usr/bin/echo \$i;
done;
/usr/bin/date +'AFTER LOOP: %T'"
''')
p.consumeProcessOutput(System.out, System.err)
(0..<8).each {
Thread.sleep(500)
print '.'
}
p.waitFor()
println "AFTER PROCESS"
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#LFE
|
LFE
|
(defun mutiply (a b)
(* a b))
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#TestML
|
TestML
|
%TestML 0.1.0
Print("Hello world!")
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Haskell
|
Haskell
|
import System.Posix.Process
main = do
forkProcess (putStrLn "This is the new process")
putStrLn "This is the original process"
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#HicEst
|
HicEst
|
SYSTEM( RUN )
WRITE(Messagebox='?Y', IOStat=ios) "Another Fork?"
IF(ios == 2) ALARM(999) ! quit immediately
! assume this script is stored as 'Fork.hic'
SYSTEM(SHell='Fork.hic')
BEEP("c e g 'c")
WRITE(Messagebox="!") "Waiting ..."
ALARM(999) ! quit immediately
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Liberty_BASIC
|
Liberty BASIC
|
' define & call a function
print multiply( 3, 1.23456)
wait
function multiply( m1, m2)
multiply =m1 *m2
end function
end
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#TI-83_BASIC
|
TI-83 BASIC
|
Disp "Hello world!
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#C
|
C
|
#include <ctype.h>
#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <glib.h>
typedef uint64_t integer;
typedef struct number_names_tag {
const char* cardinal;
const char* ordinal;
} number_names;
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
{ "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
{ "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
{ "twelve", "twelfth" }, { "thirteen", "thirteenth" },
{ "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
{ "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
{ "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};
const number_names tens[] = {
{ "twenty", "twentieth" }, { "thirty", "thirtieth" },
{ "forty", "fortieth" }, { "fifty", "fiftieth" },
{ "sixty", "sixtieth" }, { "seventy", "seventieth" },
{ "eighty", "eightieth" }, { "ninety", "ninetieth" }
};
typedef struct named_number_tag {
const char* cardinal;
const char* ordinal;
integer number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", "hundredth", 100 },
{ "thousand", "thousandth", 1000 },
{ "million", "millionth", 1000000 },
{ "billion", "biliionth", 1000000000 },
{ "trillion", "trillionth", 1000000000000 },
{ "quadrillion", "quadrillionth", 1000000000000000ULL },
{ "quintillion", "quintillionth", 1000000000000000000ULL }
};
const char* get_small_name(const number_names* n, bool ordinal) {
return ordinal ? n->ordinal : n->cardinal;
}
const char* get_big_name(const named_number* n, bool ordinal) {
return ordinal ? n->ordinal : n->cardinal;
}
const named_number* get_named_number(integer n) {
const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return &named_numbers[i];
}
return &named_numbers[names_len - 1];
}
typedef struct word_tag {
size_t offset;
size_t length;
} word_t;
typedef struct word_list_tag {
GArray* words;
GString* str;
} word_list;
void word_list_create(word_list* words) {
words->words = g_array_new(FALSE, FALSE, sizeof(word_t));
words->str = g_string_new(NULL);
}
void word_list_destroy(word_list* words) {
g_string_free(words->str, TRUE);
g_array_free(words->words, TRUE);
}
void word_list_clear(word_list* words) {
g_string_truncate(words->str, 0);
g_array_set_size(words->words, 0);
}
void word_list_append(word_list* words, const char* str) {
size_t offset = words->str->len;
size_t len = strlen(str);
g_string_append_len(words->str, str, len);
word_t word;
word.offset = offset;
word.length = len;
g_array_append_val(words->words, word);
}
word_t* word_list_get(word_list* words, size_t index) {
return &g_array_index(words->words, word_t, index);
}
void word_list_extend(word_list* words, const char* str) {
word_t* word = word_list_get(words, words->words->len - 1);
size_t len = strlen(str);
word->length += len;
g_string_append_len(words->str, str, len);
}
size_t append_number_name(word_list* words, integer n, bool ordinal) {
size_t count = 0;
if (n < 20) {
word_list_append(words, get_small_name(&small[n], ordinal));
count = 1;
} else if (n < 100) {
if (n % 10 == 0) {
word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal));
} else {
word_list_append(words, get_small_name(&tens[n/10 - 2], false));
word_list_extend(words, "-");
word_list_extend(words, get_small_name(&small[n % 10], ordinal));
}
count = 1;
} else {
const named_number* num = get_named_number(n);
integer p = num->number;
count += append_number_name(words, n/p, false);
if (n % p == 0) {
word_list_append(words, get_big_name(num, ordinal));
++count;
} else {
word_list_append(words, get_big_name(num, false));
++count;
count += append_number_name(words, n % p, ordinal);
}
}
return count;
}
size_t count_letters(word_list* words, size_t index) {
const word_t* word = word_list_get(words, index);
size_t letters = 0;
const char* s = words->str->str + word->offset;
for (size_t i = 0, n = word->length; i < n; ++i) {
if (isalpha((unsigned char)s[i]))
++letters;
}
return letters;
}
void sentence(word_list* result, size_t count) {
static const char* words[] = {
"Four", "is", "the", "number", "of", "letters", "in", "the",
"first", "word", "of", "this", "sentence,"
};
word_list_clear(result);
size_t n = sizeof(words)/sizeof(words[0]);
for (size_t i = 0; i < n; ++i)
word_list_append(result, words[i]);
for (size_t i = 1; count > n; ++i) {
n += append_number_name(result, count_letters(result, i), false);
word_list_append(result, "in");
word_list_append(result, "the");
n += 2;
n += append_number_name(result, i + 1, true);
// Append a comma to the final word
word_list_extend(result, ",");
}
}
size_t sentence_length(const word_list* words) {
size_t n = words->words->len;
if (n == 0)
return 0;
return words->str->len + n - 1;
}
int main() {
setlocale(LC_ALL, "");
size_t n = 201;
word_list result = { 0 };
word_list_create(&result);
sentence(&result, n);
printf("Number of letters in first %'lu words in the sequence:\n", n);
for (size_t i = 0; i < n; ++i) {
if (i != 0)
printf("%c", i % 25 == 0 ? '\n' : ' ');
printf("%'2lu", count_letters(&result, i));
}
printf("\nSentence length: %'lu\n", sentence_length(&result));
for (n = 1000; n <= 10000000; n *= 10) {
sentence(&result, n);
const word_t* word = word_list_get(&result, n - 1);
const char* s = result.str->str + word->offset;
printf("The %'luth word is '%.*s' and has %lu letters. ", n,
(int)word->length, s, count_letters(&result, n - 1));
printf("Sentence length: %'lu\n" , sentence_length(&result));
}
word_list_destroy(&result);
return 0;
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
if (fork()|runerr(500)) = 0 then
write("child")
else {
delay(1000)
write("parent")
}
end
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#J
|
J
|
load'dll'
Fork =: (('Error'"_)`('Parent'"_)`)(@.([: >: [: * '/lib/x86_64-linux-gnu/libc-2.19.so __fork > x' cd [: i. 0&[))
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Lily
|
Lily
|
define multiply(a: Integer, b: Integer): Integer
{
return a * b
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Lingo
|
Lingo
|
on multiply (a, b)
return a * b
end
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#TI-89_BASIC
|
TI-89 BASIC
|
Disp "Hello world!"
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#C.2B.2B
|
C++
|
#include <cctype>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
struct number_names {
const char* cardinal;
const char* ordinal;
};
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
{ "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
{ "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
{ "twelve", "twelfth" }, { "thirteen", "thirteenth" },
{ "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
{ "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
{ "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};
const number_names tens[] = {
{ "twenty", "twentieth" }, { "thirty", "thirtieth" },
{ "forty", "fortieth" }, { "fifty", "fiftieth" },
{ "sixty", "sixtieth" }, { "seventy", "seventieth" },
{ "eighty", "eightieth" }, { "ninety", "ninetieth" }
};
struct named_number {
const char* cardinal;
const char* ordinal;
uint64_t number;
};
const named_number named_numbers[] = {
{ "hundred", "hundredth", 100 },
{ "thousand", "thousandth", 1000 },
{ "million", "millionth", 1000000 },
{ "billion", "biliionth", 1000000000 },
{ "trillion", "trillionth", 1000000000000 },
{ "quadrillion", "quadrillionth", 1000000000000000ULL },
{ "quintillion", "quintillionth", 1000000000000000000ULL }
};
const char* get_name(const number_names& n, bool ordinal) {
return ordinal ? n.ordinal : n.cardinal;
}
const char* get_name(const named_number& n, bool ordinal) {
return ordinal ? n.ordinal : n.cardinal;
}
const named_number& get_named_number(uint64_t n) {
constexpr size_t names_len = std::size(named_numbers);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return named_numbers[i];
}
return named_numbers[names_len - 1];
}
size_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) {
size_t count = 0;
if (n < 20) {
result.push_back(get_name(small[n], ordinal));
count = 1;
}
else if (n < 100) {
if (n % 10 == 0) {
result.push_back(get_name(tens[n/10 - 2], ordinal));
} else {
std::string name(get_name(tens[n/10 - 2], false));
name += "-";
name += get_name(small[n % 10], ordinal);
result.push_back(name);
}
count = 1;
} else {
const named_number& num = get_named_number(n);
uint64_t p = num.number;
count += append_number_name(result, n/p, false);
if (n % p == 0) {
result.push_back(get_name(num, ordinal));
++count;
} else {
result.push_back(get_name(num, false));
++count;
count += append_number_name(result, n % p, ordinal);
}
}
return count;
}
size_t count_letters(const std::string& str) {
size_t letters = 0;
for (size_t i = 0, n = str.size(); i < n; ++i) {
if (isalpha(static_cast<unsigned char>(str[i])))
++letters;
}
return letters;
}
std::vector<std::string> sentence(size_t count) {
static const char* words[] = {
"Four", "is", "the", "number", "of", "letters", "in", "the",
"first", "word", "of", "this", "sentence,"
};
std::vector<std::string> result;
result.reserve(count + 10);
size_t n = std::size(words);
for (size_t i = 0; i < n && i < count; ++i) {
result.push_back(words[i]);
}
for (size_t i = 1; count > n; ++i) {
n += append_number_name(result, count_letters(result[i]), false);
result.push_back("in");
result.push_back("the");
n += 2;
n += append_number_name(result, i + 1, true);
result.back() += ',';
}
return result;
}
size_t sentence_length(const std::vector<std::string>& words) {
size_t n = words.size();
if (n == 0)
return 0;
size_t length = n - 1;
for (size_t i = 0; i < n; ++i)
length += words[i].size();
return length;
}
int main() {
std::cout.imbue(std::locale(""));
size_t n = 201;
auto result = sentence(n);
std::cout << "Number of letters in first " << n << " words in the sequence:\n";
for (size_t i = 0; i < n; ++i) {
if (i != 0)
std::cout << (i % 25 == 0 ? '\n' : ' ');
std::cout << std::setw(2) << count_letters(result[i]);
}
std::cout << '\n';
std::cout << "Sentence length: " << sentence_length(result) << '\n';
for (n = 1000; n <= 10000000; n *= 10) {
result = sentence(n);
const std::string& word = result[n - 1];
std::cout << "The " << n << "th word is '" << word << "' and has "
<< count_letters(word) << " letters. ";
std::cout << "Sentence length: " << sentence_length(result) << '\n';
}
return 0;
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Java
|
Java
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class RFork {
public static void main(String[] args) {
ProcessBuilder pb;
Process pp;
List<String> command;
Map<String, String> env;
BufferedReader ir;
String currentuser;
String line;
try {
command = Arrays.asList("");
pb = new ProcessBuilder(command);
env = pb.environment();
currentuser = env.get("USER");
command = Arrays.asList("ps", "-f", "-U", currentuser);
pb.command(command);
pp = pb.start();
ir = new BufferedReader(new InputStreamReader(pp.getInputStream()));
line = "Output of running " + command.toString() + " is:";
do {
System.out.println(line);
} while ((line = ir.readLine()) != null);
}
catch (IOException iox) {
iox.printStackTrace();
}
return;
}
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#LiveCode
|
LiveCode
|
function multiplyy n1 n2
return n1 * n2
end multiplyy
put multiplyy(2,5) -- = 10
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Locomotive_Basic
|
Locomotive Basic
|
10 DEF FNmultiply(x,y)=x*y
20 PRINT FNmultiply(2,PI)
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Tiny_BASIC
|
Tiny BASIC
|
10 PRINT "Hello, World!"
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Go
|
Go
|
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
f := NewFourIsSeq()
fmt.Print("The lengths of the first 201 words are:")
for i := 1; i <= 201; i++ {
if i%25 == 1 {
fmt.Printf("\n%3d: ", i)
}
_, n := f.WordLen(i)
fmt.Printf(" %2d", n)
}
fmt.Println()
fmt.Println("Length of sentence so far:", f.TotalLength())
/* For debugging:
log.Println("sentence:", strings.Join(f.words, " "))
for i, w := range f.words {
log.Printf("%3d: %2d %q\n", i, countLetters(w), w)
}
log.Println(f.WordLen(2202))
log.Println("len(f.words):", len(f.words))
log.Println("sentence:", strings.Join(f.words, " "))
*/
for i := 1000; i <= 1e7; i *= 10 {
w, n := f.WordLen(i)
fmt.Printf("Word %8d is %q, with %d letters.", i, w, n)
fmt.Println(" Length of sentence so far:", f.TotalLength())
}
}
type FourIsSeq struct {
i int // index of last word processed
words []string // strings.Join(words," ") gives the sentence so far
}
func NewFourIsSeq() *FourIsSeq {
return &FourIsSeq{
//words: strings.Fields("Four is the number of letters in the first word of this sentence,"),
words: []string{
"Four", "is", "the", "number",
"of", "letters", "in", "the",
"first", "word", "of", "this", "sentence,",
},
}
}
// WordLen returns the w'th word and its length (only counting letters).
func (f *FourIsSeq) WordLen(w int) (string, int) {
for len(f.words) < w {
f.i++
n := countLetters(f.words[f.i])
ns := say(int64(n))
os := sayOrdinal(int64(f.i+1)) + ","
// append something like: "two in the second,"
f.words = append(f.words, strings.Fields(ns)...)
f.words = append(f.words, "in", "the")
f.words = append(f.words, strings.Fields(os)...)
}
word := f.words[w-1]
return word, countLetters(word)
}
// TotalLength returns the total number of characters (including blanks,
// commas, and punctuation) of the sentence so far constructed.
func (f FourIsSeq) TotalLength() int {
cnt := 0
for _, w := range f.words {
cnt += len(w) + 1
}
return cnt - 1
}
func countLetters(s string) int {
cnt := 0
for _, r := range s {
if unicode.IsLetter(r) {
cnt++
}
}
return cnt
}
// ...
// the contents of
// https://rosettacode.org/wiki/Spelling_of_ordinal_numbers#Go
// omitted from this listing
// ...
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Julia
|
Julia
|
println("Parent running.")
@async(begin sleep(1); println("This is the child process."); sleep(2); println("Child again.") end)
sleep(2)
println("This is the parent process again.")
sleep(2)
println("Parent again.")
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Kotlin
|
Kotlin
|
// version 1.1.51
import java.io.InputStreamReader
import java.io.BufferedReader
import java.io.IOException
fun main(args: Array<String>) {
try {
val pb = ProcessBuilder()
val currentUser = pb.environment().get("USER")
val command = listOf("ps", "-f", "U", currentUser)
pb.command(command)
val proc = pb.start()
val isr = InputStreamReader(proc.inputStream)
val br = BufferedReader(isr)
var line: String? = "Output of running $command is:"
while(true) {
println(line)
line = br.readLine()
if (line == null) break
}
}
catch (iox: IOException) {
iox.printStackTrace()
}
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Logo
|
Logo
|
to multiply :x :y
output :x * :y
end
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#LSE64
|
LSE64
|
multiply : *
multiply. : *. # floating point
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#TMG
|
TMG
|
begin: parse(( = { <Hello, World!> * } ));
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#11l
|
11l
|
print(‘#05.3’.format(7.125))
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Haskell
|
Haskell
|
import Data.Char
sentence = start ++ foldMap add (zip [2..] $ tail $ words sentence)
where
start = "Four is the number of letters in the first word of this sentence, "
add (i, w) = unwords [spellInteger (alphaLength w), "in the", spellOrdinal i ++ ", "]
alphaLength w = fromIntegral $ length $ filter isAlpha w
main = mapM_ (putStrLn . say) [1000,10000,100000,1000000]
where
ws = words sentence
say n =
let (a, w:_) = splitAt (n-1) ws
in "The " ++ spellOrdinal n ++ " word is \"" ++ w ++ "\" which has " ++
spellInteger (alphaLength w) ++ " letters. The sentence length is " ++
show (length $ unwords a) ++ " chars."
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Lasso
|
Lasso
|
local(mydata = 'I am data one')
split_thread => {
loop(2) => {
sleep(2000)
stdoutnl(#mydata)
#mydata = 'Oh, looks like I am in a new thread'
}
}
loop(2) => {
sleep(3000)
stdoutnl(#mydata)
#mydata = 'Aha, I am still in the original thread'
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#LFE
|
LFE
|
(defun start ()
(spawn (lambda () (child))))
(defun child ()
(lfe_io:format "This is the new process~n" '()))
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Lua
|
Lua
|
function multiply( a, b )
return a * b
end
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#TorqueScript
|
TorqueScript
|
echo("Hello world!");
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#8086_Assembly
|
8086 Assembly
|
.model small
.stack 1024
.data
;data segment is unused in this program
.code
start:
mov ax,@code
mov ds,ax
mov es,ax
cld ;make lodsb, etc. auto-increment
mov al, byte ptr [ds:LeadingZeroes]
mov cl,al
mov ch,0
mov al,'0' ;30h
jcxz DonePrintingLeadingZeroes ;there are leading zeroes so we won't skip that section. This branch is not taken.
printLeadingZeroes:
call PrintChar ;print ascii 0 to the terminal 4 times
loop printLeadingZeroes
DonePrintingLeadingZeroes:
mov si, offset TestString
call PrintString
mov al, byte ptr [ds:TrailingZeroes]
mov cl,al
mov ch,0
mov al,'0' ;30h
jcxz DonePrintingTrailingZeroes ;there are none in this example so this branch is always taken
printTrailingZeroes:
call PrintChar
loop printTrailingZeroes
DonePrintingTrailingZeroes:
mov ax,4C00h
int 21h ;exit to DOS
TestString byte "7.125",0
LeadingZeroes byte 4 ;number of leading zeroes to print
TrailingZeroes byte 0 ;number of trailing zeroes to print
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Java
|
Java
|
import java.util.HashMap;
import java.util.Map;
public class FourIsTheNumberOfLetters {
public static void main(String[] args) {
String [] words = neverEndingSentence(201);
System.out.printf("Display the first 201 numbers in the sequence:%n%3d: ", 1);
for ( int i = 0 ; i < words.length ; i++ ) {
System.out.printf("%2d ", numberOfLetters(words[i]));
if ( (i+1) % 25 == 0 ) {
System.out.printf("%n%3d: ", i+2);
}
}
System.out.printf("%nTotal number of characters in the sentence is %d%n", characterCount(words));
for ( int i = 3 ; i <= 7 ; i++ ) {
int index = (int) Math.pow(10, i);
words = neverEndingSentence(index);
String last = words[words.length-1].replace(",", "");
System.out.printf("Number of letters of the %s word is %d. The word is \"%s\". The sentence length is %,d characters.%n", toOrdinal(index), numberOfLetters(last), last, characterCount(words));
}
}
@SuppressWarnings("unused")
private static void displaySentence(String[] words, int lineLength) {
int currentLength = 0;
for ( String word : words ) {
if ( word.length() + currentLength > lineLength ) {
String first = word.substring(0, lineLength-currentLength);
String second = word.substring(lineLength-currentLength);
System.out.println(first);
System.out.print(second);
currentLength = second.length();
}
else {
System.out.print(word);
currentLength += word.length();
}
if ( currentLength == lineLength ) {
System.out.println();
currentLength = 0;
}
System.out.print(" ");
currentLength++;
if ( currentLength == lineLength ) {
System.out.println();
currentLength = 0;
}
}
System.out.println();
}
private static int numberOfLetters(String word) {
return word.replace(",","").replace("-","").length();
}
private static long characterCount(String[] words) {
int characterCount = 0;
for ( int i = 0 ; i < words.length ; i++ ) {
characterCount += words[i].length() + 1;
}
// Extra space counted in last loop iteration
characterCount--;
return characterCount;
}
private static String[] startSentence = new String[] {"Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,"};
private static String[] neverEndingSentence(int wordCount) {
String[] words = new String[wordCount];
int index;
for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {
words[index] = startSentence[index];
}
int sentencePosition = 1;
while ( index < wordCount ) {
// X in the Y
// X
sentencePosition++;
String word = words[sentencePosition-1];
for ( String wordLoop : numToString(numberOfLetters(word)).split(" ") ) {
words[index] = wordLoop;
index++;
if ( index == wordCount ) {
break;
}
}
// in
words[index] = "in";
index++;
if ( index == wordCount ) {
break;
}
// the
words[index] = "the";
index++;
if ( index == wordCount ) {
break;
}
// Y
for ( String wordLoop : (toOrdinal(sentencePosition) + ",").split(" ") ) {
words[index] = wordLoop;
index++;
if ( index == wordCount ) {
break;
}
}
}
return words;
}
private static final String[] nums = new String[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String numToString(long n) {
return numToStringHelper(n);
}
private static final String numToStringHelper(long n) {
if ( n < 0 ) {
return "negative " + numToStringHelper(-n);
}
int index = (int) n;
if ( n <= 19 ) {
return nums[index];
}
if ( n <= 99 ) {
return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : "");
}
String label = null;
long factor = 0;
if ( n <= 999 ) {
label = "hundred";
factor = 100;
}
else if ( n <= 999999) {
label = "thousand";
factor = 1000;
}
else if ( n <= 999999999) {
label = "million";
factor = 1000000;
}
else if ( n <= 999999999999L) {
label = "billion";
factor = 1000000000;
}
else if ( n <= 999999999999999L) {
label = "trillion";
factor = 1000000000000L;
}
else if ( n <= 999999999999999999L) {
label = "quadrillion";
factor = 1000000000000000L;
}
else {
label = "quintillion";
factor = 1000000000000000000L;
}
return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : "");
}
private static Map<String,String> ordinalMap = new HashMap<>();
static {
ordinalMap.put("one", "first");
ordinalMap.put("two", "second");
ordinalMap.put("three", "third");
ordinalMap.put("five", "fifth");
ordinalMap.put("eight", "eighth");
ordinalMap.put("nine", "ninth");
ordinalMap.put("twelve", "twelfth");
}
private static String toOrdinal(long n) {
String spelling = numToString(n);
String[] split = spelling.split(" ");
String last = split[split.length - 1];
String replace = "";
if ( last.contains("-") ) {
String[] lastSplit = last.split("-");
String lastWithDash = lastSplit[1];
String lastReplace = "";
if ( ordinalMap.containsKey(lastWithDash) ) {
lastReplace = ordinalMap.get(lastWithDash);
}
else if ( lastWithDash.endsWith("y") ) {
lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth";
}
else {
lastReplace = lastWithDash + "th";
}
replace = lastSplit[0] + "-" + lastReplace;
}
else {
if ( ordinalMap.containsKey(last) ) {
replace = ordinalMap.get(last);
}
else if ( last.endsWith("y") ) {
replace = last.substring(0, last.length() - 1) + "ieth";
}
else {
replace = last + "th";
}
}
split[split.length - 1] = replace;
return String.join(" ", split);
}
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Lua
|
Lua
|
local posix = require 'posix'
local pid = posix.fork()
if pid == 0 then
print("child process")
elseif pid > 0 then
print("parent process")
else
error("unable to fork")
end
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
commandstring = First[$CommandLine] <> " -noprompt -run \"Put[Factorial[20],ToFileName[$TemporaryDirectory,ToString[temp1]]];Quit[]\""
->"MathKernel -noprompt -run \"Put[Factorial[20],ToFileName[$TemporaryDirectory,ToString[temp1]]];Quit[]\""
Run[commandstring]
->0
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Lucid
|
Lucid
|
multiply(x,y) = x * y
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#TPP
|
TPP
|
Hello world!
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Ada
|
Ada
|
with Generic_Rational;
generic
with package Rational_Numbers is new Generic_Rational (<>);
package Generic_Taylor_Series is
use Rational_Numbers;
type Taylor_Series is array (Natural range <>) of Rational;
function "+" (A : Taylor_Series) return Taylor_Series;
function "-" (A : Taylor_Series) return Taylor_Series;
function "+" (A, B : Taylor_Series) return Taylor_Series;
function "-" (A, B : Taylor_Series) return Taylor_Series;
function "*" (A, B : Taylor_Series) return Taylor_Series;
function Integral (A : Taylor_Series) return Taylor_Series;
function Differential (A : Taylor_Series) return Taylor_Series;
function Value (A : Taylor_Series; X : Rational) return Rational;
Zero : constant Taylor_Series := (0 => Rational_Numbers.Zero);
One : constant Taylor_Series := (0 => Rational_Numbers.One);
end Generic_Taylor_Series;
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#8th
|
8th
|
7.125 "%09.3f" s:strfmt
. cr
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#AArch64_Assembly
|
AArch64 Assembly
|
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program formatNum64.s */
/* use C library printf ha, ha, ha !!! */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szFormat1: .asciz " %09.3f\n"
.align 4
sfNumber: .double 0f-7125E-3
sfNumber1: .double 0f7125E-3
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszFormat1 // format
ldr x1,qAdrsfNumber // float number address
ldr d0,[x1] // load float number in d0
bl printf // call C function !!!
ldr x0,qAdrszFormat1
ldr x1,qAdrsfNumber1
ldr d0,[x1]
bl printf
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszFormat1: .quad szFormat1
qAdrsfNumber: .quad sfNumber
qAdrsfNumber1: .quad sfNumber1
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Julia
|
Julia
|
using DataStructures # for deque
const seed = "Four is the number of letters in the first word of this sentence, "
const (word2, word3) = ("in", "the")
lettercount(w) = length(w) - length(collect(eachmatch(r"-", w)))
splits(txt) = [x.match for x in eachmatch(r"[\w\-]+", txt)]
todq(sentence) = (d = Deque{String}(); map(x->push!(d, x), splits(sentence)[2:end]); d)
struct CountLetters
seedsentence::String
words::Deque{String}
commasafter::Vector{Int}
CountLetters(s) = new(s, todq(s), [13])
CountLetters() = CountLetters(seed)
end
function Base.iterate(iter::CountLetters, state = (1, 5, ""))
if length(iter.words) < 1
return nothing
end
returnword = popfirst!(iter.words)
nextwordindex = state[1] + 1
wordlen = lettercount(returnword)
wordvec = vcat(num2text(wordlen), word2, word3, splits(numtext2ordinal(num2text(nextwordindex))))
map(x -> push!(iter.words, x), wordvec)
push!(iter.commasafter, length(iter.words))
added = length(returnword) + (nextwordindex in iter.commasafter ? 2 : 1)
(wordlen, (nextwordindex, state[2] + added, returnword))
end
Base.eltype(iter::CountLetters) = Int
function firstN(n = 201)
countlet = CountLetters()
print("It is interesting how identical lengths align with 20 columns.\n 1: 4")
iter_result = iterate(countlet)
itercount = 2
while iter_result != nothing
(wlen, state) = iter_result
print(lpad(string(wlen), 4))
if itercount % 20 == 0
print("\n", lpad(itercount+1, 4), ":")
elseif itercount >= n
break
end
iter_result = iterate(countlet, state)
itercount += 1
end
println()
end
function sumwords(iterations)
countlet = CountLetters()
iter_result = iterate(countlet)
itercount = 2
while iter_result != nothing
(wlen, state) = iter_result
if itercount == iterations
return state
end
iter_result = iterate(countlet, state)
itercount += 1
end
throw("Iteration failed on \"Four is the number\" task.")
end
firstN()
for n in [2202, 1000, 10000, 100000, 1000000, 10000000]
(itercount, totalletters, lastword) = sumwords(n)
println("$n words -> $itercount iterations, $totalletters letters total, ",
"last word \"$lastword\" with $(length(lastword)) letters.")
end
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Kotlin
|
Kotlin
|
// version 1.1.4-3
val names = mapOf(
1 to "one",
2 to "two",
3 to "three",
4 to "four",
5 to "five",
6 to "six",
7 to "seven",
8 to "eight",
9 to "nine",
10 to "ten",
11 to "eleven",
12 to "twelve",
13 to "thirteen",
14 to "fourteen",
15 to "fifteen",
16 to "sixteen",
17 to "seventeen",
18 to "eighteen",
19 to "nineteen",
20 to "twenty",
30 to "thirty",
40 to "forty",
50 to "fifty",
60 to "sixty",
70 to "seventy",
80 to "eighty",
90 to "ninety"
)
val bigNames = mapOf(
1_000L to "thousand",
1_000_000L to "million",
1_000_000_000L to "billion",
1_000_000_000_000L to "trillion",
1_000_000_000_000_000L to "quadrillion",
1_000_000_000_000_000_000L to "quintillion"
)
val irregOrdinals = mapOf(
"one" to "first",
"two" to "second",
"three" to "third",
"five" to "fifth",
"eight" to "eighth",
"nine" to "ninth",
"twelve" to "twelfth"
)
fun String.toOrdinal(): String {
if (this == "zero") return "zeroth" // or alternatively 'zeroeth'
val splits = this.split(' ', '-')
val last = splits[splits.lastIndex]
return if (irregOrdinals.containsKey(last)) this.dropLast(last.length) + irregOrdinals[last]!!
else if (last.endsWith("y")) this.dropLast(1) + "ieth"
else this + "th"
}
fun numToText(n: Long, uk: Boolean = false): String {
if (n == 0L) return "zero"
val neg = n < 0L
val maxNeg = n == Long.MIN_VALUE
var nn = if (maxNeg) -(n + 1) else if (neg) -n else n
val digits3 = IntArray(7)
for (i in 0..6) { // split number into groups of 3 digits from the right
digits3[i] = (nn % 1000).toInt()
nn /= 1000
}
fun threeDigitsToText(number: Int) : String {
val sb = StringBuilder()
if (number == 0) return ""
val hundreds = number / 100
val remainder = number % 100
if (hundreds > 0) {
sb.append(names[hundreds], " hundred")
if (remainder > 0) sb.append(if (uk) " and " else " ")
}
if (remainder > 0) {
val tens = remainder / 10
val units = remainder % 10
if (tens > 1) {
sb.append(names[tens * 10])
if (units > 0) sb.append("-", names[units])
}
else sb.append(names[remainder])
}
return sb.toString()
}
val strings = Array(7) { threeDigitsToText(digits3[it]) }
var text = strings[0]
var andNeeded = uk && digits3[0] in 1..99
var big = 1000L
for (i in 1..6) {
if (digits3[i] > 0) {
var text2 = strings[i] + " " + bigNames[big]
if (text.isNotEmpty()) {
text2 += if (andNeeded) " and " else " " // no commas inserted in this version
andNeeded = false
}
else andNeeded = uk && digits3[i] in 1..99
text = text2 + text
}
big *= 1000
}
if (maxNeg) text = text.dropLast(5) + "eight"
if (neg) text = "minus " + text
return text
}
val opening = "Four is the number of letters in the first word of this sentence,".split(' ')
val String.adjustedLength get() = this.replace(",", "").replace("-", "").length // no ',' or '-'
fun getWords(n: Int): List<String> {
val words = mutableListOf<String>()
words.addAll(opening)
if (n > opening.size) {
var k = 2
while (true) {
val len = words[k - 1].adjustedLength
val text = numToText(len.toLong())
val splits = text.split(' ')
words.addAll(splits)
words.add("in")
words.add("the")
val text2 = numToText(k.toLong()).toOrdinal() + "," // add trailing comma
val splits2 = text2.split(' ')
words.addAll(splits2)
if (words.size >= n) break
k++
}
}
return words
}
fun getLengths(n: Int): Pair<List<Int>, Int> {
val words = getWords(n)
val lengths = words.take(n).map { it.adjustedLength }
val sentenceLength = words.sumBy { it.length } + words.size - 1 // includes hyphens, commas & spaces
return Pair(lengths, sentenceLength)
}
fun getLastWord(n: Int): Triple<String, Int, Int> {
val words = getWords(n)
val nthWord = words[n - 1]
val nthWordLength = nthWord.adjustedLength
val sentenceLength = words.sumBy { it.length } + words.size - 1 // includes hyphens, commas & spaces
return Triple(nthWord, nthWordLength, sentenceLength)
}
fun main(args: Array<String>) {
var n = 201
println("The lengths of the first $n words are:\n")
val (list, sentenceLength) = getLengths(n)
for (i in 0 until n) {
if (i % 25 == 0) {
if (i > 0) println()
print("${"%3d".format(i + 1)}: ")
}
print("%3d".format(list[i]))
}
println("\n\nLength of sentence = $sentenceLength\n")
n = 1_000
do {
var (word, wLen, sLen) = getLastWord(n)
if (word.endsWith(",")) word = word.dropLast(1) // strip off any trailing comma
println("The length of word $n [$word] is $wLen")
println("Length of sentence = $sLen\n")
n *= 10
}
while (n <= 10_000_000)
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
do
pb = ProcessBuilder([String ''])
env = pb.environment()
currentuser = String env.get('USER')
command = Arrays.asList([String 'ps', '-f', '-U', currentuser])
pb.command(command)
pp = pb.start()
ir = BufferedReader(InputStreamReader(pp.getInputStream()))
line = String 'Output of running' command.toString() 'is:'
loop label w_ until line = null
say line
line = ir.readLine()
end w_
catch iox = IOException
iox.printStackTrace()
end
return
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#NewLISP
|
NewLISP
|
(let (pid (fork (println "Hello from child")))
(cond
((nil? pid) (throw-error "Unable to fork"))
('t (wait-pid pid))))
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module Checkit {
Module Multiply (a, b) {
Push a*b
}
Multiply 10, 5
Print Number=50
Module Multiply {
Push Number*Number
}
Multiply 10, 5
Print Number=50
\\ push before call
Push 10, 5
Multiply
Read A
Print A=50
Push 10, 2,3 : Multiply : Multiply: Print Number=60
Module Multiply {
If not match("NN") Then Error "I nead two numbers"
Read a, b
Push a*b
}
Call Multiply 10, 5
Print Number=50
\\ now there are two values in stack 20 and 50
Multiply
}
Call Checkit, 20, 50
Print Number=1000
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Transact-SQL
|
Transact-SQL
|
PRINT "Hello world!"
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h> /* for NaN */
enum fps_type {
FPS_CONST = 0,
FPS_ADD,
FPS_SUB,
FPS_MUL,
FPS_DIV,
FPS_DERIV,
FPS_INT,
};
typedef struct fps_t *fps;
typedef struct fps_t {
int type;
fps s1, s2;
double a0;
} fps_t;
fps fps_new()
{
fps x = malloc(sizeof(fps_t));
x->a0 = 0;
x->s1 = x->s2 = 0;
x->type = 0;
return x;
}
/* language limit of C; when self or mutual recursive definition is needed,
* one has to be defined, then defined again after it's used. See how
* sin and cos are defined this way below
*/
void fps_redefine(fps x, int op, fps y, fps z)
{
x->type = op;
x->s1 = y;
x->s2 = z;
}
fps _binary(fps x, fps y, int op)
{
fps s = fps_new();
s->s1 = x;
s->s2 = y;
s->type = op;
return s;
}
fps _unary(fps x, int op)
{
fps s = fps_new();
s->s1 = x;
s->type = op;
return s;
}
/* Taking the n-th term of series. This is where actual work is done. */
double term(fps x, int n)
{
double ret = 0;
int i;
switch (x->type) {
case FPS_CONST: return n > 0 ? 0 : x->a0;
case FPS_ADD:
ret = term(x->s1, n) + term(x->s2, n); break;
case FPS_SUB:
ret = term(x->s1, n) - term(x->s2, n); break;
case FPS_MUL:
for (i = 0; i <= n; i++)
ret += term(x->s1, i) * term(x->s2, n - i);
break;
case FPS_DIV:
if (! term(x->s2, 0)) return NAN;
ret = term(x->s1, n);
for (i = 1; i <= n; i++)
ret -= term(x->s2, i) * term(x, n - i) / term(x->s2, 0);
break;
case FPS_DERIV:
ret = n * term(x->s1, n + 1);
break;
case FPS_INT:
if (!n) return x->a0;
ret = term(x->s1, n - 1) / n;
break;
default:
fprintf(stderr, "Unknown operator %d\n", x->type);
exit(1);
}
return ret;
}
#define _add(x, y) _binary(x, y, FPS_ADD)
#define _sub(x, y) _binary(x, y, FPS_SUB)
#define _mul(x, y) _binary(x, y, FPS_MUL)
#define _div(x, y) _binary(x, y, FPS_DIV)
#define _integ(x) _unary(x, FPS_INT)
#define _deriv(x) _unary(x, FPS_DERIV)
fps fps_const(double a0)
{
fps x = fps_new();
x->type = FPS_CONST;
x->a0 = a0;
return x;
}
int main()
{
int i;
fps one = fps_const(1);
fps fcos = fps_new(); /* cosine */
fps fsin = _integ(fcos); /* sine */
fps ftan = _div(fsin, fcos); /* tangent */
/* redefine cos to complete the mutual recursion; maybe it looks
* better if I said
* *fcos = *( _sub(one, _integ(fsin)) );
*/
fps_redefine(fcos, FPS_SUB, one, _integ(fsin));
fps fexp = fps_const(1); /* exponential */
/* make exp recurse on self */
fps_redefine(fexp, FPS_INT, fexp, 0);
printf("Sin:"); for (i = 0; i < 10; i++) printf(" %g", term(fsin, i));
printf("\nCos:"); for (i = 0; i < 10; i++) printf(" %g", term(fcos, i));
printf("\nTan:"); for (i = 0; i < 10; i++) printf(" %g", term(ftan, i));
printf("\nExp:"); for (i = 0; i < 10; i++) printf(" %g", term(fexp, i));
return 0;
}
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Ada
|
Ada
|
with Ada.Text_Io.Editing; use Ada.Text_Io.Editing;
with Ada.Text_Io; use Ada.Text_Io;
procedure Zero_Fill is
Pic_String: String := "<999999.99>";
Pic : Picture := To_Picture(Pic_String);
type Money is delta 0.01 digits 8;
package Money_Output is new Decimal_Output(Money);
use Money_Output;
Value : Money := 37.25;
begin
Put(Item => Value, Pic => Pic);
end Zero_Fill;
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Aime
|
Aime
|
o_form("/w9s0/\n", 7.125);
o_form("/w12d6p6/\n", -12.0625);
o_form("/w12d6p6/\n", 7.125);
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
(*==Number names==*)
(*Mathematica has a built-in function for getting the name of an integer. It's a semantically rich function (dealing with many languages and grammatical variants), and consequently it would slow down our algorithm significantly. So, I've used the built-in function to seed/memoize special-purpose functions. Furthermore, the problem is suited to using a representation of the sentence that is an array of strings rather than a single monolithic string, and so these integer name functions will return arrays of strings.*)
(*We'll define the function for small integers to use the built-in function and to trigger memoization on the first invocation. After that, the basic strategy is to chunk up an integer into groups of three digits, apply the name to what those digits usually represent and then add the 'scaling' term (e.g. 'thousand', 'million'). Just for laziness, I'll skip trying to handle the 'thousand and zero' case and just fall back to the built-in function--it shouldn't be called often enough to matter. Since this problem won't need number names exceeding the 'million' scale, I won't optimize beyond that.*)
IntNameWords[n_]:=(IntNameWords[n]=StringSplit[IntegerName[n,"Words"]])/;n<1000;
IntNameWords[n_]:=StringSplit[IntegerName[n,"Words"]]/;Divisible[n,1000];
IntNameWords[n_]:=Flatten[Riffle[IntNameWords/@QuotientRemainder[n,1000],"thousand"]]/;n<1000000;
IntNameWords[n_]:=Flatten[Riffle[IntNameWords/@QuotientRemainder[n,1000000],"million"]]/;n<1000000000;
IntNameWords[n_]:=StringSplit[IntegerName[n,"Words"]];
(*I'm using Scan to trigger the memoization.*)
Scan[IntNameWords,Range[999]];
(*The strategy is similar for ordinals. Note that I'm tacking on a comma to the ordinals. This makes this function quite specialized to this specific problem.*)
OrdNameWords[n_]:=(OrdNameWords[n]=StringSplit[IntegerName[n,"Ordinal"]<>","])/;n<1000;
OrdNameWords[n_]:=StringSplit[IntegerName[n,"Ordinal"]<>","]/;Divisible[n,1000];
OrdNameWords[n_]:=Flatten[Riffle[Construct@@@Thread[{{IntNameWords,OrdNameWords},QuotientRemainder[n,1000]}],"thousand"]]/;n<1000000;
OrdNameWords[n_]:=Flatten[Riffle[Construct@@@Thread[{{IntNameWords,OrdNameWords},QuotientRemainder[n,1000000]}],"million"]]/;n<1000000000;
OrdNameWords[n_]:=StringSplit[IntegerName[n,"Ordinal"]<>","];
(*Triggering memoization again.*)
Scan[OrdNameWords,Range[999]];
(*==Helper/driver functions==*)
(*This could be generalized, but for this problem, the '-' and ',' are the only non-letter characters we need to worry about.*)
LetterCount[str_]:=StringLength[StringDelete[str,"-"|","]];
(*The seed/initial part of the sentence.*)
SentenceHeadWords=StringSplit["Four is the number of letters in the first word of this sentence,"];
(*Output formatters*)
DisplayWordLengthSequence[wordSeq_]:=StringRiffle[{"First "<>StringRiffle[IntNameWords[Length@wordSeq]]<>" numbers in sequence:",LetterCount/@wordSeq},"\n"];
DisplayCharacterCount[wordSeq_]:=StringRiffle[{"String length of sentence with "<>StringRiffle[IntNameWords[Length@wordSeq]]<>" words:",SentenceCharacterCount[wordSeq]}];
DisplayWordInfo[wordSeq_,wordIdx_]:=StringForm["The `` word is '``' consisting of `` letters.",StringRiffle[OrdNameWords[Length@wordSeq]],wordSeq[[wordIdx]],StringRiffle[IntNameWords[StringLength@wordSeq[[wordIdx]]]]];
(*There is a space between each 'word', so we can just add 1 less than the number of 'words' to get total characters in the full string representation of the sentence (if we were to create it). I could also subract another 1 for the trailing comma, but the requirements weren't precise in this regard.*)
SentenceCharacterCount[chunks:{__String}]:=Total[StringLength[chunks]]+Length[chunks]-1;
(*==Implementation A==*)
(*A simple functional implementation that continues to extend the 'sentence' one fragment at a time until the number of words exceeds the requested number. This implementation takes several seconds to complete the 100,000 word case.*)
ExtendCharChunks[{0,0,{}}]={1,Length[SentenceHeadWords],SentenceHeadWords};
ExtendCharChunks[{fragCt_,wordCt_,chunks_}]:=
With[
{nextFrag=Flatten[{IntNameWords[LetterCount[chunks[[1+fragCt]]]],"in","the",OrdNameWords[1+fragCt]}]},
{1+fragCt,wordCt+Length[nextFrag],Flatten[{chunks,nextFrag}]}
];
SentenceChunksFun[chunkCt_]:=Take[Last[NestWhile[ExtendCharChunks,ExtendCharChunks[{0,0,{}}],#[[2]]<chunkCt&]],chunkCt];
(*==Implementation B==*)
(*This implementation uses a pre-allocated array, an iterative strategy, and inlining of the fragment construction. It performs much better than the previous implementation but still takes about 20 seconds for the 10 million word case. One could try compiling the function for greater performance.*)
SentenceChunksArray[targetCount_]:=
Block[
{
chunks=ConstantArray["",targetCount],
wordIdx=0,
fragmentIdx=0
},
Scan[(chunks[[++wordIdx]]=#)&,SentenceHeadWords];
++fragmentIdx;
While[
(*Since each new fragment is longer than one word, it is likely that we will try to insert more words into the array than it has been allocated to hold. This generates and error message, but does not otherwise interfere with processing (the insertion simply fails). I could include more checks, but it didn't seem necessary for this task.*)
wordIdx<targetCount,
Scan[(chunks[[++wordIdx]]=#)&,{Splice[IntNameWords[LetterCount[chunks[[++fragmentIdx]]]]],"in","the",Splice[OrdNameWords[fragmentIdx]]}]
];
chunks
];
(*==Output==*)
StringRiffle[
{
DisplayWordLengthSequence[SentenceChunksArray[201]],
DisplayCharacterCount[SentenceChunksArray[201]],
DisplayWordInfo[SentenceChunksArray[1000],1000],
DisplayWordInfo[SentenceChunksArray[10000],10000],
DisplayWordInfo[SentenceChunksArray[100000],100000],
DisplayWordInfo[SentenceChunksArray[1000000],1000000],
DisplayWordInfo[SentenceChunksArray[10000000],10000000]
},
"\n\n"
]
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Nim
|
Nim
|
import posix
var pid = fork()
if pid < 0:
echo "Error forking a child"
elif pid > 0:
echo "This is the parent process and its child has id ", pid, '.'
# Further parent stuff.
else:
echo "This is the child process."
# Further child stuff.
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#OCaml
|
OCaml
|
#load "unix.cma";;
let pid = Unix.fork ();;
if pid > 0 then
print_endline "This is the original process"
else
print_endline "This is the new process";;
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#M4
|
M4
|
define(`multiply',`eval($1*$2)')
multiply(2,3)
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Transd
|
Transd
|
(textout "Hello, World!")
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Clojure
|
Clojure
|
(defn ps+ [ps0 ps1]
(letfn [(+zs [ps] (concat ps (repeat :z)))
(notz? [a] (not= :z a))
(nval [a] (if (notz? a) a 0))
(z+ [a0 a1] (if (= :z a0 a1) :z (+ (nval a0) (nval a1))))]
(take-while notz? (map z+ (+zs ps0) (+zs ps1)))))
(defn ps- [ps0 ps1] (ps+ ps0 (map - ps1)))
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#ALGOL_68
|
ALGOL 68
|
main:(
REAL r=exp(pi)-pi;
print((r,newline));
printf(($g(-16,4)l$,-r));
printf(($g(-16,4)l$,r));
printf(($g( 16,4)l$,r));
printf(($g( 16,4,1)l$,r));
printf(($-dddd.ddddl$,-r));
printf(($-dddd.ddddl$,r));
printf(($+dddd.ddddl$,r));
printf(($ddddd.ddddl$,r));
printf(($zzzzd.ddddl$,r));
printf(($zzzz-d.ddddl$,r));
printf(($zzzz-d.ddddedl$,r));
printf(($zzzz-d.ddddeddl$,r));
printf(($4z-d.4de4dl$,r))
)
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Nim
|
Nim
|
import strutils, strformat, tables
####################################################################################################
# Cardinal and ordinal strings.
const
Small = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
Tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
Illions = ["", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion"]
IrregularOrdinals = {"one": "first", "two": "second", "three": "third", "five": "fifth",
"eight": "eighth", "nine": "ninth", "twelve": "twelfth"}.toTable()
#---------------------------------------------------------------------------------------------------
func spellCardinal(n: int64): string =
## Spell an integer as a cardinal.
var n = n
if n < 0:
result = "negative "
n = -n
if n < 20:
result &= Small[n]
elif n < 100:
result &= Tens[n div 10]
let m = n mod 10
if m != 0: result &= '-' & Small[m]
elif n < 1000:
result &= Small[n div 100] & " hundred"
let m = n mod 100
if m != 0: result &= ' ' & m.spellCardinal()
else:
# Work from right to left.
var sx = ""
var i = 0
while n > 0:
let m = n mod 1000
n = n div 1000
if m != 0:
var ix = m.spellCardinal() & Illions[i]
if sx.len > 0: ix &= " " & sx
sx = ix
inc i
result &= sx
#---------------------------------------------------------------------------------------------------
func spellOrdinal(n: int64): string =
## Spell an integer as an ordinal.
result = n.spellCardinal()
var parts = result.rsplit({' ', '-'}, maxsplit = 1)
let tail = parts[^1]
if tail in IrregularOrdinals:
result[^tail.len..^1] = IrregularOrdinals[tail]
elif tail.endsWith('y'):
result[^1..^1]= "ieth"
else:
result &= "th"
####################################################################################################
# Sentence building.
type Sentence = seq[string]
#---------------------------------------------------------------------------------------------------
iterator words(sentence: var Sentence): tuple[idx: int; word: string] =
## Yield the successive words of the sentence with their index.
yield (0, "Four")
var idx = 1
var last = 0
while true:
yield (idx, sentence[idx])
inc idx
if idx == sentence.len:
inc last
sentence.add([sentence[last].count(Letters).spellCardinal(), "in", "the"])
# For the position, we need to split the ordinal as it may contain spaces.
sentence.add(((last + 1).spellOrdinal() & ',').splitWhitespace())
#---------------------------------------------------------------------------------------------------
iterator letterCounts(sentence: var Sentence): tuple[idx: int; word: string; count: int] =
## Secondary iterator used to yield the number of letters in addition to the index and the word.
for i, word in sentence.words():
yield (i, word, word.count(Letters))
####################################################################################################
# Drivers.
# Constant to initialize the sentence.
const Init = "Four is the number of letters in the first word of this sentence,".splitWhitespace()
#---------------------------------------------------------------------------------------------------
proc displayLetterCounts(pos: Positive) =
## Display the number of letters of the word at position "pos".
var sentence = Init
echo fmt"Number of letters in first {pos} words in the sequence:"
var valcount = 0 # Number of values displayed in the current line.
var length = 0
for i, word, letterCount in sentence.letterCounts():
if i == pos:
# Terminated.
dec length # Adjust space count.
echo ""
break
if valcount == 0: stdout.write fmt"{i+1:>3}:"
stdout.write fmt"{letterCount:>3}"
inc valcount
inc length, word.len + 1 # +1 for space.
if valcount == 12:
# Terminate line.
echo ""
valcount = 0
echo fmt"Length of sentence: {length}"
#---------------------------------------------------------------------------------------------------
proc displayWord(pos: Positive) =
## Display the word at position "pos".
var sentence = Init
let idx = pos - 1
var length = 0
for i, word in sentence.words():
length += word.len + 1
if i == idx:
dec length # Adjust space count.
let w = word.strip(leading = false, chars = {','}) # Remove trailing ',' if needed.
echo fmt"Word {pos} is ""{w}"" with {w.count(Letters)} letters."
echo fmt"Length of sentence: {length}"
break
#———————————————————————————————————————————————————————————————————————————————————————————————————
displayLetterCounts(201)
for n in [1_000, 10_000, 100_000, 1_000_000, 10_000_000]:
echo ""
displayWord(n)
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Perl
|
Perl
|
use feature 'state';
use Lingua::EN::Numbers qw(num2en num2en_ordinal);
my @sentence = split / /, 'Four is the number of letters in the first word of this sentence, ';
sub extend_to {
my($last) = @_;
state $index = 1;
until ($#sentence > $last) {
push @sentence, split ' ', num2en(alpha($sentence[$index])) . ' in the ' . no_c(num2en_ordinal(1+$index)) . ',';
$index++;
}
}
sub alpha { my($s) = @_; $s =~ s/\W//gi; length $s }
sub no_c { my($s) = @_; $s =~ s/\ and|,//g; return $s }
sub count { length(join ' ', @sentence[0..-1+$_[0]]) . " characters in the sentence, up to and including this word.\n" }
print "First 201 word lengths in the sequence:\n";
extend_to(201);
for (0..200) {
printf "%3d", alpha($sentence[$_]);
print "\n" unless ($_+1) % 32;
}
print "\n" . count(201) . "\n";
for (1e3, 1e4, 1e5, 1e6, 1e7) {
extend_to($_);
print
ucfirst(num2en_ordinal($_)) . " word, '$sentence[$_-1]' has " . alpha($sentence[$_-1]) . " characters. \n" .
count($_) . "\n";
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#ooRexx
|
ooRexx
|
sub=.fork~new
sub~sub
Call syssleep 1
Do 3
Say 'program ' time()
Call syssleep 1
End
::class fork
:: method sub
Reply
Do 6
Say 'subroutine' time()
Call syssleep 1
End
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Oz
|
Oz
|
declare
ParentVar1 = "parent data"
ParentVar2
functor RemoteCode
export
result:Result
import QTk at 'x-oz://system/wp/QTk.ozf'
define
Result
%% Show a simple window. When it is closed by the user, set Result.
Window =
{QTk.build
td(action:proc {$} Result = 42 end %% on close
label(text:"In child process: "#ParentVar1))} %% read parent process variable
{Window show}
!ParentVar2 = childData %% write to parent process variable
{Wait Result}
end
%% create a new process on the same machine
RM = {New Remote.manager init(host:localhost)}
%% execute the code encapsulated in the given functor
RemoteModule = {RM apply(RemoteCode $)}
in
%% retrieve data from child process
{Show RemoteModule.result} %% prints 42
%% exit child process
{RM close}
{Show ParentVar2} %% print "childData"
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#MAD
|
MAD
|
INTERNAL FUNCTION MULT.(A,B) = A * B
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#TransFORTH
|
TransFORTH
|
PRINT " Hello world! "
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Common_Lisp
|
Common Lisp
|
(defpackage #:formal-power-series
(:nicknames #:fps)
(:use "COMMON-LISP")
(:shadow
#:+ #:- #:* #:/))
(in-package #:formal-power-series)
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#AmigaE
|
AmigaE
|
PROC newRealF(es, fl, digit, len=0, zeros=TRUE)
DEF s, t, i
IF (len = 0) OR (len < (digit+3))
RETURN RealF(es, fl, digit)
ELSE
s := String(len)
t := RealF(es, fl, digit)
FOR i := 0 TO len-EstrLen(t)-1 DO StrAdd(s, IF zeros THEN '0' ELSE ' ')
StrAdd(s, t)
StrCopy(es, s)
DisposeLink(s)
DisposeLink(t)
ENDIF
ENDPROC es
PROC main()
DEF s[100] : STRING
WriteF('\s\n', newRealF(s, 7.125, 3,9))
ENDPROC
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Phix
|
Phix
|
with javascript_semantics
include demo\rosetta\number_names.exw -- see note
-- as per Spelling_of_ordinal_numbers#Phix:
constant {irregs,ordinals} = columnize({{"one","first"},
{"two","second"},
{"three","third"},
{"five","fifth"},
{"eight","eighth"},
{"nine","ninth"},
{"twelve","twelfth"}})
function ordinl(string s)
integer i
for i=length(s) to 1 by -1 do
integer ch = s[i]
if ch=' ' or ch='-' then exit end if
end for
integer k = find(s[i+1..$],irregs)
if k then
s = s[1..i]&ordinals[k]
elsif s[$]='y' then
s[$..$] = "ieth"
else
s &= "th"
end if
return s
end function
--/copy of Spelling_of_ordinal_numers#Phix
function count_letters(string s)
integer res = 0
for i=1 to length(s) do
integer ch = s[i]
if (ch>='A' and ch<='Z')
or (ch>='a' and ch<='z') then
res += 1
end if
end for
return res
end function
sequence words = split("Four is the number of letters in the first word of this sentence,")
integer fi = 1
function kill_and(sequence s)
--grr...
for i=length(s) to 1 by -1 do
if s[i] = "and" then
s[i..i] = {}
end if
end for
return s
end function
function word_len(integer w)
-- Returns the w'th word and its length (only counting letters).
while length(words)<w do
fi += 1
integer n = count_letters(words[fi])
sequence ns = kill_and(split(spell(n)))
sequence os = kill_and(split(ordinl(spell(fi)) & ","))
-- append eg {"two","in","the","second,"}
words &= ns&{"in","the"}&os
end while
string word = words[w]
return {word, count_letters(word)}
end function
function total_length()
-- Returns the total number of characters (including blanks,
-- commas, and punctuation) of the sentence so far constructed.
integer res = 0
for i=1 to length(words) do
res += length(words[i])+1
end for
return res
end function
procedure main()
printf(1,"The lengths of the first 201 words are:\n")
for i=1 to 201 do
if mod(i,25)==1 then
printf(1,"\n%3d: ", i)
end if
printf(1," %2d", word_len(i)[2])
end for
printf(1,"\nLength of sentence so far:%d\n", total_length())
for p=3 to iff(platform()=JS?5:7) do
integer i = power(10,p)
{string w, integer n} = word_len(i)
printf(1,"Word %8d is \"%s\", with %d letters.", {i, w, n})
printf(1," Length of sentence so far:%d\n", total_length())
end for
end procedure
main()
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#PARI.2FGP
|
PARI/GP
|
void
foo()
{
if (pari_daemon())
pari_printf("Original\n");
else
pari_printf("Fork\n");
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Perl
|
Perl
|
FORK:
if ($pid = fork()) {
# parent code
} elsif (defined($pid)) {
setsid; # tells apache to let go of this process and let it run solo
# disconnect ourselves from input, output, and errors
close(STDOUT);
close(STDIN);
close(STDERR);
# re-open to /dev/null to prevent irrelevant warn messages.
open(STDOUT, '>/dev/null');
open(STDIN, '>/dev/null');
open(STDERR, '>>/home/virtual/logs/err.log');
# child code
exit; # important to exit
} elsif($! =~ /emporar/){
warn '[' . localtime() . "] Failed to Fork - Will try again in 10 seconds.\n";
sleep(10);
goto FORK;
} else {
warn '[' . localtime() . "] Unable to fork - $!";
exit(0);
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Make
|
Make
|
A=1
B=1
multiply:
@expr $(A) \* $(B)
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Trith
|
Trith
|
"Hello world!" print
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#D
|
D
|
(require 'math)
;; converts a finite polynomial (a_0 a_1 .. a_n) to an infinite serie (a_0 ..a_n 0 0 0 ...)
(define (poly->stream list)
(make-stream (lambda(n) (cons (if (< n (length list)) (list-ref list n) 0) (1+ n))) 0))
;; c = a + b , c_n = a_n + b_n
(define (s-add a b)
(make-stream (lambda (n) (cons (+ (stream-ref a n) (stream-ref b n)) (1+ n))) 0))
;; c = a * b , c_n = ∑ (0 ..n) a_i * b_n-i
(define (s-mul-coeff n a b) (sigma (lambda(i) (* (stream-ref a i)(stream-ref b (- n i)))) 0 n))
(define (s-mul a b)
(make-stream (lambda(n) (cons (s-mul-coeff n a b) (1+ n))) 0))
;; b = 1/a ; b_0 = 1/a_0, b_n = - ∑ (1..n) a_i * b_n-i / a_0
(define (s-inv-coeff n a b)
(if (zero? n) (/ (stream-ref a 0))
(- (/ (sigma (lambda(i) (* (stream-ref a i)(stream-ref b (- n i)))) 1 n)
(stream-ref a 0)))))
;; note the self keyword which refers to b = (s-inv a)
(define (s-inv a)
(make-stream (lambda(n) (cons (s-inv-coeff n a self ) (1+ n))) 0))
;; b = (s-k-add k a) = k + a_0, a_1, a_2, ...
(define (s-k-add k a)
(make-stream (lambda(n) (cons
(if(zero? n) (+ k (stream-ref a 0)) (stream-ref a n)) (1+ n))) 0))
;; b = (s-neg a) = -a_0,-a_1, ....
(define (s-neg a)
(make-stream (lambda(n) (cons (- (stream-ref a n)) (1+ n))) 0))
;; b = (s-int a) = ∫ a ; b_0 = 0 by convention, b_n = a_n-1/n
(define (s-int a)
(make-stream (lambda(n) (cons (if (zero? n) 0 (/ (stream-ref a (1- n)) n)) (1+ n))) 0))
;; value of power serie at x, n terms
(define (s-value a x (n 20))
(poly x (take a n)))
;; stream-cons allows mutual delayed references
;; sin = ∫ cos
(define sin-x (stream-cons 0 (stream-rest (s-int cos-x))))
;; cos = 1 - ∫ sin
(define cos-x (stream-cons 1 (stream-rest (s-k-add 1 (s-neg (s-int sin-x))))))
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#APL
|
APL
|
'ZF15.9' ⎕FMT 7.125
00007.125000000
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#ARM_Assembly
|
ARM Assembly
|
/* ARM assembly Raspberry PI */
/* program formatNum.s */
/* use C library printf ha, ha, ha !!! */
/* Constantes */
.equ EXIT, 1 @ Linux syscall
/* Initialized data */
.data
szFormat1: .asciz " %09.3f\n"
.align 4
sfNumber: .double 0f-7125E-3
sfNumber1: .double 0f7125E-3
/* UnInitialized data */
.bss
.align 4
/* code section */
.text
.global main
main: @ entry of program
push {fp,lr} @ saves registers
ldr r0,iAdrszFormat1 @ format
ldr r1,iAdrsfNumber @ number address
ldr r2,[r1] @ load first 4 bytes
ldr r3,[r1,#4] @ load last 4 bytes
bl printf @ call C function !!!
ldr r0,iAdrszFormat1
ldr r1,iAdrsfNumber1
ldr r2,[r1]
ldr r3,[r1,#4]
bl printf
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @restaur registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszFormat1: .int szFormat1
iAdrsfNumber: .int sfNumber
iAdrsfNumber1: .int sfNumber1
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Python
|
Python
|
# Python implementation of Rosetta Code Task
# http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
# Uses inflect
# https://pypi.org/project/inflect/
import inflect
def count_letters(word):
"""
count letters ignore , or -, or space
"""
count = 0
for letter in word:
if letter != ',' and letter !='-' and letter !=' ':
count += 1
return count
def split_with_spaces(sentence):
"""
Takes string with partial sentence and returns
list of words with spaces included.
Leading space is attached to first word.
Later spaces attached to prior word.
"""
sentence_list = []
curr_word = ""
for c in sentence:
if c == " " and curr_word != "":
# append space to end of non-empty words
# assumed no more than 1 consecutive space.
sentence_list.append(curr_word+" ")
curr_word = ""
else:
curr_word += c
# add trailing word that does not end with a space
if len(curr_word) > 0:
sentence_list.append(curr_word)
return sentence_list
def my_num_to_words(p, my_number):
"""
Front end to inflect's number_to_words
Get's rid of ands and commas in large numbers.
"""
number_string_list = p.number_to_words(my_number, wantlist=True, andword='')
number_string = number_string_list[0]
for i in range(1,len(number_string_list)):
number_string += " " + number_string_list[i]
return number_string
def build_sentence(p, max_words):
"""
Builds at most max_words of the task following the pattern:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth,
"""
# start with first part of sentence up first comma as a list
sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,")
num_words = 13
# which word number we are doing next
# two/second is first one in loop
word_number = 2
# loop until sentance is at least as long as needs be
while num_words < max_words:
# Build something like
# ,two in the second
# get second or whatever we are on
ordinal_string = my_num_to_words(p, p.ordinal(word_number))
# get two or whatever the length is of the word_number word
word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))
# sentence addition
new_string = " "+word_number_string+" in the "+ordinal_string+","
new_list = split_with_spaces(new_string)
sentence_list += new_list
# add new word count
num_words += len(new_list)
# increment word number
word_number += 1
return sentence_list, num_words
def word_and_counts(word_num):
"""
Print's lines like this:
Word 1000 is "in", with 2 letters. Length of sentence so far: 6279
"""
sentence_list, num_words = build_sentence(p, word_num)
word_str = sentence_list[word_num - 1].strip(' ,')
num_letters = len(word_str)
num_characters = 0
for word in sentence_list:
num_characters += len(word)
print('Word {0:8d} is "{1}", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters))
p = inflect.engine()
sentence_list, num_words = build_sentence(p, 201)
print(" ")
print("The lengths of the first 201 words are:")
print(" ")
print('{0:3d}: '.format(1),end='')
total_characters = 0
for word_index in range(201):
word_length = count_letters(sentence_list[word_index])
total_characters += len(sentence_list[word_index])
print('{0:2d}'.format(word_length),end='')
if (word_index+1) % 20 == 0:
# newline every 20
print(" ")
print('{0:3d}: '.format(word_index + 2),end='')
else:
print(" ",end='')
print(" ")
print(" ")
print("Length of the sentence so far: "+str(total_characters))
print(" ")
"""
Expected output this part:
Word 1000 is "in", with 2 letters. Length of the sentence so far: 6279
Word 10000 is "in", with 2 letters. Length of the sentence so far: 64140
Word 100000 is "one", with 3 letters. Length of the sentence so far: 659474
Word 1000000 is "the", with 3 letters. Length of the sentence so far: 7113621
Word 10000000 is "thousand", with 8 letters. Length of the sentence so far: 70995756
"""
word_and_counts(1000)
word_and_counts(10000)
word_and_counts(100000)
word_and_counts(1000000)
word_and_counts(10000000)
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Phix
|
Phix
|
without js
procedure mythread()
?"mythread"
exit_thread(0)
end procedure
atom hThread = create_thread(routine_id("mythread"),{})
?"main carries on"
wait_thread(hThread)
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#PHP
|
PHP
|
<?php
$pid = pcntl_fork();
if ($pid == 0)
echo "This is the new process\n";
else if ($pid > 0)
echo "This is the original process\n";
else
echo "ERROR: Something went wrong\n";
?>
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Maple
|
Maple
|
multiply:= (a, b) -> a * b;
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#True_BASIC
|
True BASIC
|
! In True BASIC all programs run in their own window. So this is almost a graphical version.
PRINT "Hello world!"
END
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#EchoLisp
|
EchoLisp
|
(require 'math)
;; converts a finite polynomial (a_0 a_1 .. a_n) to an infinite serie (a_0 ..a_n 0 0 0 ...)
(define (poly->stream list)
(make-stream (lambda(n) (cons (if (< n (length list)) (list-ref list n) 0) (1+ n))) 0))
;; c = a + b , c_n = a_n + b_n
(define (s-add a b)
(make-stream (lambda (n) (cons (+ (stream-ref a n) (stream-ref b n)) (1+ n))) 0))
;; c = a * b , c_n = ∑ (0 ..n) a_i * b_n-i
(define (s-mul-coeff n a b) (sigma (lambda(i) (* (stream-ref a i)(stream-ref b (- n i)))) 0 n))
(define (s-mul a b)
(make-stream (lambda(n) (cons (s-mul-coeff n a b) (1+ n))) 0))
;; b = 1/a ; b_0 = 1/a_0, b_n = - ∑ (1..n) a_i * b_n-i / a_0
(define (s-inv-coeff n a b)
(if (zero? n) (/ (stream-ref a 0))
(- (/ (sigma (lambda(i) (* (stream-ref a i)(stream-ref b (- n i)))) 1 n)
(stream-ref a 0)))))
;; note the self keyword which refers to b = (s-inv a)
(define (s-inv a)
(make-stream (lambda(n) (cons (s-inv-coeff n a self ) (1+ n))) 0))
;; b = (s-k-add k a) = k + a_0, a_1, a_2, ...
(define (s-k-add k a)
(make-stream (lambda(n) (cons
(if(zero? n) (+ k (stream-ref a 0)) (stream-ref a n)) (1+ n))) 0))
;; b = (s-neg a) = -a_0,-a_1, ....
(define (s-neg a)
(make-stream (lambda(n) (cons (- (stream-ref a n)) (1+ n))) 0))
;; b = (s-int a) = ∫ a ; b_0 = 0 by convention, b_n = a_n-1/n
(define (s-int a)
(make-stream (lambda(n) (cons (if (zero? n) 0 (/ (stream-ref a (1- n)) n)) (1+ n))) 0))
;; value of power serie at x, n terms
(define (s-value a x (n 20))
(poly x (take a n)))
;; stream-cons allows mutual delayed references
;; sin = ∫ cos
(define sin-x (stream-cons 0 (stream-rest (s-int cos-x))))
;; cos = 1 - ∫ sin
(define cos-x (stream-cons 1 (stream-rest (s-k-add 1 (s-neg (s-int sin-x))))))
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Arturo
|
Arturo
|
r: 7.125
print r
print to :string .format: "09.3f" r
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#AutoHotkey
|
AutoHotkey
|
MsgBox % pad(7.25,7) ; 0007.25
MsgBox % pad(-7.25,7) ; -007.25
pad(x,len) { ; pad with 0's from left to len chars
IfLess x,0, Return "-" pad(SubStr(x,2),len-1)
VarSetCapacity(p,len,Asc("0"))
Return SubStr(p x,1-len)
}
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#11l
|
11l
|
F xor(a, b)
R (a & !b) | (b & !a)
F ha(a, b)
R (xor(a, b), a & b)
F fa(a, b, ci)
V (s0, c0) = ha(ci, a)
V (s1, c1) = ha(s0, b)
R (s1, c0 | c1)
F fa4(a, b)
V width = 4
V ci = [0B] * width
V co = [0B] * width
V s = [0B] * width
L(i) 0 .< width
(s[i], co[i]) = fa(a[i], b[i], I i != 0 {co[i - 1]} E 0)
R (s, co.last)
F int2bus(n, width = 4)
R reversed(bin(n).zfill(width)).map(c -> Int(c))
F bus2int(b)
R sum(enumerate(b).filter2((i, bit) -> bit).map2((i, bit) -> 1 << i))
V width = 4
V tot = [0B] * (width + 1)
L(a) 0 .< 2 ^ width
L(b) 0 .< 2 ^ width
V (ta, tlast) = fa4(int2bus(a), int2bus(b))
L(i) 0 .< width
tot[i] = ta[i]
tot[width] = tlast
assert(a + b == bus2int(tot), ‘totals don't match: #. + #. != #.’.format(a, b, String(tot)))
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Raku
|
Raku
|
use Lingua::EN::Numbers;
no-commas(True);
my $index = 1;
my @sentence = flat 'Four is the number of letters in the first word of this sentence, '.words,
{ @sentence[$index++].&alpha.&cardinal, 'in', 'the', |($index.&ordinal ~ ',').words } ... * ;
sub alpha ( $str ) { $str.subst(/\W/, '', :g).chars }
sub count ( $index ) { @sentence[^$index].join(' ').chars ~ " characters in the sentence, up to and including this word.\n" }
say 'First 201 word lengths in the sequence:';
put ' ', map { @sentence[$_].&alpha.fmt("%2d") ~ (((1+$_) %% 25) ?? "\n" !! '') }, ^201;
say 201.&count;
for 1e3, 1e4, 1e5, 1e6, 1e7 {
say "{.&ordinal.tc} word, '{@sentence[$_ - 1]}', has {@sentence[$_ - 1].&alpha} characters. ", .&count
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#PicoLisp
|
PicoLisp
|
(unless (fork) # In child process
(println *Pid) # Print the child's PID
(bye) ) # and terminate
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#PL.2FI
|
PL/I
|
ATTACH SOLVE (X) THREAD (T5);
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
multiply[a_,b_]:=a*b
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.