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/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #OCaml | OCaml | (*
* Caution: This is my first Ocaml program and anyone with Ocaml experience probably thinks it's horrible
* So please don't use this as an example for "good ocaml code" see it more as
* "this is what my first lines of ocaml might look like"
*
* The only reason im publishing this is that nobody has yet submitted an example in ocaml
*)
(* sfp is just a convenience to put a combination if sanitation (s) fire (f) and police (p) department in one record*)
type sfp = {s : int; f : int; p : int}
(* Convenience Function to print a single sfp Record *)
let print_sfp e =
Printf.printf "%d %d %d\n" e.s e.f e.p
(* Convenience Function to print a list of sfp Records*)
let print_sfp_list l =
l |> List.iter print_sfp
(* Computes sum of list l *)
let sum l = List.fold_left (+) 0 l
(* checks if element e is in list l *)
let element_in_list e l =
l |> List.find_map (fun x -> if x == e then Some(e) else None) <> None
(* returns a list with only the unique elements of list l *)
let uniq l =
let rec uniq_helper acc l =
match l with
| [] -> acc
| h::t -> if element_in_list h t then uniq_helper acc t else uniq_helper (h::acc) t in
uniq_helper [] l |> List.rev
(* checks wheter or not list l only contains unique elements *)
let is_uniq l = uniq l = l
(* computes all combinations for a given list of sanitation, fire & police departments
im not very proud of this function...maybe someone with some experience can clean it up? ;)
*)
let department_numbers sl fl pl =
sl |> List.fold_left (fun aa s ->
fl |> List.fold_left (fun fa f ->
pl |> List.fold_left (fun pa p ->
if
sum [s;f;p] == 12 &&
is_uniq [s;f;p] then
{s = s; f = f; p = p} :: pa
else
pa) []
|> List.append fa) []
|> List.append aa) []
(* "main" function *)
let _ =
let s = [1;2;3;4;5;6;7] in
let f = [1;2;3;4;5;6;7] in
let p = [2;4;6] in
let result = department_numbers s f p in
print_endline "S F P";
print_sfp_list result;
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Raven | Raven | 'input.txt' delete
'/input.txt' delete
'docs' rmdir
'/docs' rmdir |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #REBOL | REBOL | ; Local.
delete %input.txt
delete-dir %docs/
; Root.
delete %/input.txt
delete-dir %/docs/ |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Sidef | Sidef | func div_check(a, b){
var result = a/b
result.abs == Inf ? nil : result
}
say div_check(10, 2) # 5
say div_check(1, 0) # nil (detected) |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Slate | Slate | [ 1 / 0 ] on: Error do: [|:err| err return: PositiveInfinity]. |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Smalltalk | Smalltalk | |didDivideByZero a b|
didDivideByZero := false.
a := 10.
b := 0.
[
a/b
] on: ZeroDivide do:[:ex |
'you tried to divide %P by zero\n' printf:{ex suspendedContext receiver} on:Transcript.
didDivideByZero := true.
].
didDivideByZero ifTrue:[
Transcript show:'bad bad bad, but I already told you in the handler'.
]. |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Objective-C | Objective-C | if( [[NSScanner scannerWithString:@"-123.4e5"] scanFloat:NULL] )
NSLog( @"\"-123.4e5\" is numeric" );
else
NSLog( @"\"-123.4e5\" is not numeric" );
if( [[NSScanner scannerWithString:@"Not a number"] scanFloat:NULL] )
NSLog( @"\"Not a number\" is numeric" );
else
NSLog( @"\"Not a number\" is not numeric" );
// prints: "-123.4e5" is numeric
// prints: "Not a number" is not numeric |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #OCaml | OCaml | let is_int s =
try ignore (int_of_string s); true
with _ -> false
let is_float s =
try ignore (float_of_string s); true
with _ -> false
let is_numeric s = is_int s || is_float s |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #Wren | Wren | import "/fmt" for Fmt
var sumDigits = Fn.new { |n|
var sum = 0
while (n > 0) {
sum = sum + (n%10)
n = (n/10).floor
}
return sum
}
var digitalRoot = Fn.new { |n|
if (n < 0) Fiber.abort("Argument must be non-negative.")
if (n < 10) return [n, 0]
var dr = n
var ap = 0
while (dr > 9) {
dr = sumDigits.call(dr)
ap = ap + 1
}
return [dr, ap]
}
var a = [1, 14, 267, 8128, 627615, 39390, 588225, 393900588225]
for (n in a) {
var res = digitalRoot.call(n)
var dr = res[0]
var ap = res[1]
Fmt.print("$,15d has additive persistence $d and digital root of $d", n, ap, dr)
} |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Python | Python | def dotp(a,b):
assert len(a) == len(b), 'Vector sizes must match'
return sum(aterm * bterm for aterm,bterm in zip(a, b))
if __name__ == '__main__':
a, b = [1, 3, -5], [4, -2, -1]
assert dotp(a,b) == 3 |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #PARI.2FGP | PARI/GP | forstep(p=2,6,2, for(f=1,7, s=12-p-f; if(p!=f && p!=s && f!=s && s>0 && s<8, print(p" "f" "s)))) |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Retro | Retro | 'input.txt file:delete
'/input.txt file:delete |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #REXX | REXX | /*REXX program deletes a file and a folder in the current directory and the root. */
trace off /*suppress REXX error messages from DOS*/
aFile= 'input.txt' /*name of a file to be deleted. */
aDir = 'docs' /*name of a folder to be removed. */
do j=1 for 2 /*perform this DO loop exactly twice.*/
'ERASE' aFile /*erase this file in the current dir. */
'RMDIR' "/s /q" aDir /*remove the folder " " " " */
if j==1 then 'CD \' /*make the current dir the root dir.*/
end /* [↑] just do CD \ command once.*/
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #SNOBOL4 | SNOBOL4 | define('zdiv(x,y)') :(zdiv_end)
zdiv &errlimit = 1; setexit(.ztrap)
zdiv = x / y :(return)
ztrap zdiv = ?(&errtype ? (14 | 262)) 'Division by zero' :s(continue)f(abort)
zdiv_end
* # Test and display
output = '1/1 = ' zdiv(1,1) ;* Integers non-zero
output = '1.0/1.0 = ' zdiv(1.0,1.0) ;* Reals non-zero
output = '1/0 = ' zdiv(1,0) ;* Integers zero
output = '1.0/0.0 = ' zdiv(1.0,0.0) ;* Reals zero
output = 'Zero checks complete'
end |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #SQL_PL | SQL PL |
--#SET TERMINATOR @
SET SERVEROUTPUT ON@
CREATE OR REPLACE FUNCTION DIVISION(
IN NUMERATOR DECIMAL(5, 3),
IN DENOMINATOR DECIMAL(5, 3)
) RETURNS SMALLINT
BEGIN
DECLARE RET SMALLINT DEFAULT 1;
DECLARE TMP DECIMAL(5, 3);
DECLARE CONTINUE HANDLER FOR SQLSTATE '22012'
SET RET = 1;
SET RET = 0;
SET TMP = NUMERATOR / DENOMINATOR;
RETURN RET;
END @
VALUES DIVISION(10, 2)@
VALUES DIVISION(10, 3)@
VALUES DIVISION(10, 0)@
|
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Standard_ML | Standard ML | fun div_check (x, y) = (
ignore (x div y);
false
) handle Div => true |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Octave | Octave | function r = isnum(a)
if ( isnumeric(a) )
r = 1;
else
r = ~isnan(str2double(a));
endif
endfunction
% tests
disp(isnum(123)) % 1
disp(isnum("123")) % 1
disp(isnum("foo123")) % 0
disp(isnum("123bar")) % 0
disp(isnum("3.1415")) % 1 |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Oz | Oz | fun {IsNumeric S}
{String.isInt S} orelse {String.isFloat S}
end |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
func DRoot(N, B, P); \Return digital root and persistance P
real N, B; int P;
int S;
[P(0):= 0;
while N >= B do
[S:= 0;
repeat S:= S + fix(Mod(N,B)); \sum last digit
N:= N/B; \remove last digit
N:= N - Mod(N,1.);
until N < 0.1; \(beware of rounding errors)
P(0):= P(0)+1; \increment persistance
N:= float(S);
];
return fix(N);
];
real Tbl;
int I, Root, Pers;
[Tbl:= [627615., 39390., 588225., 393900588225.];
for I:= 0 to 4-1 do
[Root:= DRoot(Tbl(I), 10., @Pers);
IntOut(0, Pers); ChOut(0, ^ ); IntOut(0, Root); CrLf(0);
];
] |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #zkl | zkl | fcn sum(n,b){ n.split(b).sum(0) }
fcn droot(n,b=10,X=0) // -->(digital root, additive persistence)
{ if(n<b)return(n,X); return(self.fcn(sum(n,b),b,X+1)) } |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #QBasic | QBasic | DIM zero3d(2) 'some example vectors
zero3d(0) = 0!: zero3d(1) = 0!: zero3d(2) = 0!
DIM zero5d(4)
zero5d(0) = 0!: zero5d(1) = 0!: zero5d(2) = 0!: zero5d(3) = 0!: zero5d(4) = 0!
DIM x(2): x(0) = 1!: x(1) = 0!: x(2) = 0!
DIM y(2): y(0) = 0!: y(1) = 1!: y(2) = 0!
DIM z(2): z(0) = 0!: z(1) = 0!: z(2) = 1!
DIM q(2): q(0) = 1!: q(1) = 1!: q(2) = 3.14159
DIM r(2): r(0) = -1!: r(1) = 2.618033989#: r(2) = 3!
PRINT " q dot r = "; dot(q(), r())
PRINT " zero3d dot zero5d = "; dot(zero3d(), zero5d())
PRINT " zero3d dot x = "; dot(zero3d(), x())
PRINT " z dot z = "; dot(z(), z())
PRINT " y dot z = "; dot(y(), z())
FUNCTION dot (a(), b())
IF UBOUND(a) <> UBOUND(b) THEN dot = 0
dp = 0!
FOR i = 0 TO UBOUND(a)
dp = dp + (a(i) * b(i))
NEXT i
dot = dp
END FUNCTION |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Perl | Perl |
#!/usr/bin/perl
my @even_numbers;
for (1..7)
{
if ( $_ % 2 == 0)
{
push @even_numbers, $_;
}
}
print "Police\tFire\tSanitation\n";
foreach my $police_number (@even_numbers)
{
for my $fire_number (1..7)
{
for my $sanitation_number (1..7)
{
if ( $police_number + $fire_number + $sanitation_number == 12 &&
$police_number != $fire_number &&
$fire_number != $sanitation_number &&
$sanitation_number != $police_number)
{
print "$police_number\t$fire_number\t$sanitation_number\n";
}
}
}
}
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Ring | Ring |
remove("output.txt")
system("rmdir docs")
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Ruby | Ruby | File.delete("output.txt", "/output.txt")
Dir.delete("docs")
Dir.delete("/docs") |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Stata | Stata | proc div_check {x y} {
if {[catch {expr {$x/$y}} result] == 0} {
puts "valid division: $x/$y=$result"
} else {
if {$result eq "divide by zero"} {
puts "caught division by zero: $x/$y -> $result"
} else {
puts "caught another error: $x/$y -> $result"
}
}
}
foreach denom {1 0 foo} {
div_check 42 $denom
} |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Tcl | Tcl | proc div_check {x y} {
if {[catch {expr {$x/$y}} result] == 0} {
puts "valid division: $x/$y=$result"
} else {
if {$result eq "divide by zero"} {
puts "caught division by zero: $x/$y -> $result"
} else {
puts "caught another error: $x/$y -> $result"
}
}
}
foreach denom {1 0 foo} {
div_check 42 $denom
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PARI.2FGP | PARI/GP | isNumeric(s)={
my(t=type(eval(s)));
t == "t_INT" || t == "T_REAL"
}; |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Pascal | Pascal |
Built-In Function
Syntax
IsNumber(Value)
Description
Use the IsNumber function to determine if Value contains a valid numeric value. Numeric characters include sign indicators and comma and period decimal points.
To determine if a value is a number and if it's in the user's local format, use the IsUserNumber function.
Parameters
Value
Specify a string you want to search to determine if it is a valid number.
Returns
A Boolean value: True if Value contains a valid numeric value, False otherwise.
Example
&Value = Get Field().Value;
If IsNumber(&Value) Then
/* do numeric processing */
Else
/* do non-numeric processing */
End-if;
|
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #zonnon | zonnon |
module Main;
type
longint = integer{64};
type {public,ref}
Response = object (dr,p: longint)
var {public,immutable}
digitalRoot,persistence: longint;
procedure {public} Writeln;
begin
writeln("digital root: ",digitalRoot:2," persistence: ",persistence:2)
end Writeln;
begin
self.digitalRoot := dr;
self.persistence := p;
end Response;
procedure DigitalRoot(n:longint):Response;
var
sum,p: longint;
begin
p := 0;
loop
inc(p);sum := 0;
while (n > 0) do
inc(sum,n mod 10);
n := n div 10;
end;
if sum < 10 then return new Response(sum,p) else n := sum end
end
end DigitalRoot;
begin
write(627615:22,":> ");DigitalRoot(627615).Writeln;
write(39390:22,":> ");DigitalRoot(39390).Writeln;
write(588225:22,":> ");DigitalRoot(588225).Writeln;
write(max(integer{64}):22,":> ");DigitalRoot(max(integer{64})).Writeln;
end Main.
|
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DATA 4,627615,39390,588225,9992
20 READ j: LET b=10
30 FOR i=1 TO j
40 READ n
50 PRINT "Digital root of ";n;" is"
60 GO SUB 1000
70 NEXT i
80 STOP
1000 REM Digital Root
1010 LET c=0
1020 IF n>=b THEN LET c=c+1: GO SUB 2000: GO TO 1020
1030 PRINT n;" persistance is ";c''
1040 RETURN
2000 REM Digit sum
2010 LET s=0
2020 IF n<>0 THEN LET q=INT (n/b): LET s=s+n-q*b: LET n=q: GO TO 2020
2030 LET n=s
2040 RETURN |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Quackery | Quackery | [ 0 unrot witheach
[ over i^ peek *
rot + swap ]
drop ] is .prod ( [ [ --> n )
' [ 1 3 -5 ] ' [ 4 -2 -1 ] .prod echo |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #R | R | x <- c(1, 3, -5)
y <- c(4, -2, -1)
sum(x*y) # compute products, then do the sum
x %*% y # inner product
# loop implementation
dotp <- function(x, y) {
n <- length(x)
if(length(y) != n) stop("invalid argument")
s <- 0
for(i in 1:n) s <- s + x[i]*y[i]
s
}
dotp(x, y) |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Phix | Phix | printf(1,"Police Sanitation Fire\n")
printf(1,"------ ---------- ----\n")
integer solutions = 0
for police=2 to 7 by 2 do
for sanitation=1 to 7 do
if sanitation!=police then
integer fire = 12-(police+sanitation)
if fire>=1
and fire<=7
and fire!=police
and fire!=sanitation then
printf(1," %d %d %d\n", {police,sanitation,fire})
solutions += 1
end if
end if
end for
end for
printf(1,"\n%d solutions found\n", solutions)
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Run_BASIC | Run BASIC | '------ delete input.txt ----------------
kill "input.txt" ' this is where we are
kill "/input.txt" ' this is the root
' ---- delete directory docs ----------
result = rmdir("Docs") ' directory where we are
result = rmdir("/Docs") ' root directory |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Rust | Rust | use std::io::{self, Write};
use std::fs::{remove_file,remove_dir};
use std::path::Path;
use std::{process,display};
const FILE_NAME: &'static str = "output.txt";
const DIR_NAME : &'static str = "docs";
fn main() {
delete(".").and(delete("/"))
.unwrap_or_else(|e| error_handler(e,1));
}
fn delete<P>(root: P) -> io::Result<()>
where P: AsRef<Path>
{
remove_file(root.as_ref().join(FILE_NAME))
.and(remove_dir(root.as_ref().join(DIR_NAME)))
}
fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {
let _ = writeln!(&mut io::stderr(), "{:?}", error);
process::exit(code)
} |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #TXR | TXR | @(do (defun div-check (x y)
(catch (/ x y)
(numeric_error (msg)
'div-check-failed))))
@(bind good @(div-check 32 8))
@(bind bad @(div-check 42 0)) |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Ursa | Ursa | def div_check (int x, int y)
try
/ x y
return false
catch divzeroerror
return true
end try
end |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #VAX_Assembly | VAX Assembly | 65 64 69 76 69 64 00000008'010E0000' 0000 1 desc: .ascid "divide by zero"
6F 72 65 7A 20 79 62 20 000E
0000 0016 2 .entry handler,0
E5 AF 7F 0018 3 pushaq desc
00000000'GF 01 FB 001B 4 calls #1, g^lib$put_output
04 0022 5 ret
0023 6
0000 0023 7 .entry main,0
6D EE AF 9E 0025 8 movab handler, (fp) ;register exception handler
50 01 00 C7 0029 9 divl3 #0, #1, r0
04 002D 10 ret
002E 11
002E 12 .end main
$ run dv
divide by zero
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PeopleCode | PeopleCode |
Built-In Function
Syntax
IsNumber(Value)
Description
Use the IsNumber function to determine if Value contains a valid numeric value. Numeric characters include sign indicators and comma and period decimal points.
To determine if a value is a number and if it's in the user's local format, use the IsUserNumber function.
Parameters
Value
Specify a string you want to search to determine if it is a valid number.
Returns
A Boolean value: True if Value contains a valid numeric value, False otherwise.
Example
&Value = Get Field().Value;
If IsNumber(&Value) Then
/* do numeric processing */
Else
/* do non-numeric processing */
End-if;
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Perl | Perl | use Scalar::Util qw(looks_like_number);
print looks_like_number($str) ? "numeric" : "not numeric\n"; |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Racket | Racket |
#lang racket
(define (dot-product l r) (for/sum ([x l] [y r]) (* x y)))
(dot-product '(1 3 -5) '(4 -2 -1))
;; dot-product works on sequences such as vectors:
(dot-product #(1 2 3) #(4 5 6))
|
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Raku | Raku | say [+] (1, 3, -5) »*« (4, -2, -1); |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #PHP | PHP | <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL; |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Scala | Scala | import java.util._
import java.io.File
object FileDeleteTest extends App {
def deleteFile(filename: String) = { new File(filename).delete() }
def test(typ: String, filename: String) = {
System.out.println("The following " + typ + " called " + filename +
(if (deleteFile(filename)) " was deleted." else " could not be deleted."))
}
test("file", "input.txt")
test("file", File.separatorChar + "input.txt")
test("directory", "docs")
test("directory", File.separatorChar + "docs" + File.separatorChar)
} |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Scheme | Scheme | (delete-file filename) |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #VBA | VBA |
Option Explicit
Sub Main()
Dim Div
If CatchDivideByZero(152, 0, Div) Then Debug.Print Div Else Debug.Print "Error"
If CatchDivideByZero(152, 10, Div) Then Debug.Print Div Else Debug.Print "Error"
End Sub
Function CatchDivideByZero(Num, Den, Div) As Boolean
On Error Resume Next
Div = Num / Den
If Err = 0 Then CatchDivideByZero = True
On Error GoTo 0
End Function |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #VBScript | VBScript |
Function div(num,den)
On Error Resume Next
n = num/den
If Err.Number <> 0 Then
div = Err.Description & " is not allowed."
Else
div = n
End If
End Function
WScript.StdOut.WriteLine div(6,3)
WScript.StdOut.WriteLine div(6,0)
WScript.StdOut.WriteLine div(7,-4)
|
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Visual_Basic_.NET | Visual Basic .NET | Module DivByZeroDetection
Sub Main()
Console.WriteLine(safeDivision(10, 0))
End Sub
Private Function safeDivision(v1 As Integer, v2 As Integer) As Boolean
Try
Dim answer = v1 / v2
Return False
Catch ex As Exception
Return True
End Try
End Function
End Module
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Phix | Phix | function isNumber(string s)
return scanf(s,"%f")!={}
-- Alt: isNumberString(object s) and
-- return string(s) and scanf(s,"%f")!={}, or even
-- return string(s) and scanf(substitute(trim(s),",",""),"%f")!={}
end function
constant tests = {"#a","#A","0xA","0(16)A","#FF","255","0",
"0.","0.0","000.000","0e0","0e-2000"," ",
".14",".05","-5.2","0xf","ten","1B","#1B",
" 12 ",trim(" 12 "),"1","0o16","0o18",
"0b10101111_11110000_11110000_00110011",
"1_000","50e","+123","+ 123","-0b10101",
"NaN","+.345","12..34","12e3.4","0-2",
"192.168.0.1","1.2e","1 2","12.34","",
"beef","#beef","1,000,000","Inf","1/2",
"1.5e+27","0x10.5","1."}
sequence numeric = {},
notnumb = {}
for i=1 to length(tests) do
string ti = tests[i]
if isNumber(ti) then
numeric = append(numeric,ti)
else
notnumb = append(notnumb,ti)
end if
end for
puts(1,"numeric: ")
pp(numeric,{pp_Indent,9})
puts(1,"\nnot numeric: ")
pp(notnumb,{pp_Indent,13})
|
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Rascal | Rascal | import List;
public int dotProduct(list[int] L, list[int] M){
result = 0;
if(size(L) == size(M)) {
while(size(L) >= 1) {
result += (head(L) * head(M));
L = tail(L);
M = tail(M);
}
return result;
}
else {
throw "vector sizes must match";
}
} |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #REBOL | REBOL | rebol []
a: [1 3 -5]
b: [4 -2 -1]
dot-product: function [v1 v2] [sum] [
if (length? v1) != (length? v2) [
make error! "error: vector sizes must match"
]
sum: 0
repeat i length? v1 [
sum: sum + ((pick v1 i) * (pick v2 i))
]
]
dot-product a b |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Picat | Picat | import cp.
go ?=>
N = 7,
Sols = findall([P,S,F], department_numbers(N, P,S,F)),
println(" P S F"),
foreach([P,S,F] in Sols)
printf("%2d %2d %2d\n",P,S,F)
end,
nl,
printf("Number of solutions: %d\n", Sols.len),
nl.
go => true.
department_numbers(N, Police,Sanitation,Fire) =>
Police :: 1..N,
Sanitation :: 1..N,
Fire :: 1..N,
all_different([Police,Sanitation,Fire]),
Police + Sanitation + Fire #= 12,
Police mod 2 #= 0,
solve([Police,Sanitation,Fire]). |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #PicoLisp | PicoLisp | (de numbers NIL
(co 'numbers
(let N 7
(for P N
(for S N
(for F N
(yield (list P S F)) ) ) ) ) ) )
(de departments NIL
(use (L)
(while (setq L (numbers))
(or
(bit? 1 (car L))
(= (car L) (cadr L))
(= (car L) (caddr L))
(= (cadr L) (caddr L))
(<> 12 (apply + L))
(println L) ) ) ) )
(departments) |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "osfiles.s7i";
const proc: main is func
begin
removeFile("input.txt");
removeFile("/input.txt");
removeTree("docs");
removeTree("/docs");
end func; |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #SenseTalk | SenseTalk | // Delete locally (relative to "the folder")
delete file "input.txt"
delete folder "docs"
// Delete at the file system root
delete file "/input.txt"
delete folder "/docs"
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Sidef | Sidef | # here
%f'input.txt' -> delete;
%d'docs' -> delete;
# root dir
Dir.root + %f'input.txt' -> delete;
Dir.root + %d'docs' -> delete; |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Wren | Wren | var checkDivByZero = Fn.new { |a, b|
var c = a / b
if (c.isInfinity || c.isNan) return true
return false
}
System.print("Division by zero?")
System.print(" 0 / 0 -> %(checkDivByZero.call(0, 0))")
System.print(" 1 / 0 -> %(checkDivByZero.call(1, 0))")
System.print(" 1 / 1 -> %(checkDivByZero.call(1, 1))") |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #XPL0 | XPL0 | include c:\cxpl\codes;
int A, B;
[Trap(false); \turn off error trapping
B:= 1234/(A-A); \(error not detected at compile time)
if GetErr then Text(0, "Divide by zero");
] |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Yorick | Yorick | func div_check(x, y) {
if(catch(0x01))
return 1;
temp = x/y;
return 0;
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PHP | PHP | <?php
$string = '123';
if(is_numeric(trim($string))) {
}
?> |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PicoLisp | PicoLisp | : (format "123")
-> 123
: (format "123a45")
-> NIL
: (format "-123.45" 4)
-> 1234500 |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #REXX | REXX | /*REXX program computes the dot product of two equal size vectors (of any size).*/
vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/
vectorB = ' 4 -2 -1 ' /* " " B " " " */
say 'vector A = ' vectorA /*display the elements in the vector A.*/
say 'vector B = ' vectorB /* " " " " " " B.*/
p=.Prod(vectorA, vectorB) /*invoke function & compute dot product*/
say /*display a blank line for readability.*/
say 'dot product = ' p /*display the dot product to terminal. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.Prod: procedure; parse arg A,B /*this function compute the dot product*/
$=0 /*initialize the sum to 0 (zero). */
do j=1 for words(A) /*multiply each number in the vectors. */
$=$+word(A,j) * word(B,j) /* ··· and add the product to the sum.*/
end /*j*/
return $ /*return the sum to function's invoker.*/ |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Prolog | Prolog |
dept(X) :- between(1, 7, X).
police(X) :- member(X, [2, 4, 6]).
fire(X) :- dept(X).
san(X) :- dept(X).
assign(A, B, C) :-
police(A), fire(B), san(C),
A =\= B, A =\= C, B =\= C,
12 is A + B + C.
main :-
write("P F S"), nl,
forall(assign(Police, Fire, Sanitation), format("~w ~w ~w~n", [Police, Fire, Sanitation])),
halt.
?- main.
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Slate | Slate | (File newNamed: 'input.txt') delete.
(File newNamed: '/input.txt') delete.
(Directory newNamed: 'docs') delete.
(Directory newNamed: '/docs') delete. |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Smalltalk | Smalltalk | File remove: 'input.txt'.
File remove: 'docs'.
File remove: '/input.txt'.
File remove: '/docs' |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #zkl | zkl | fcn f(x,y){try{x/y}catch(MathError){println(__exception)}} |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Pike | Pike |
int(0..1) is_number(string s)
{
array test = array_sscanf(s, "%s%f%s");
if (sizeof(test) == 3 && test[1] && !sizeof(test[0]) && !sizeof(test[2]) )
return true;
else
return false;
}
string num = "-1.234"
is_number(num);
-> true
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PL.2FI | PL/I |
is_numeric: procedure (text) returns (bit (1));
declare text character (*);
declare x float;
on conversion go to done;
get string(text) edit (x) (E(length(text),0));
return ('1'b);
done:
return ('0'b);
end is_numeric; |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Ring | Ring |
aVector = [2, 3, 5]
bVector = [4, 2, 1]
sum = 0
see dotProduct(aVector, bVector)
func dotProduct cVector, dVector
for n = 1 to len(aVector)
sum = sum + cVector[n] * dVector[n]
next
return sum
|
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #RLaB | RLaB | x = rand(1,10);
y = rand(1,10);
s = sum( x .* y ); |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Python | Python | from itertools import permutations
def solve():
c, p, f, s = "\\,Police,Fire,Sanitation".split(',')
print(f"{c:>3} {p:^6} {f:^4} {s:^10}")
c = 1
for p, f, s in permutations(range(1, 8), r=3):
if p + s + f == 12 and p % 2 == 0:
print(f"{c:>3}: {p:^6} {f:^4} {s:^10}")
c += 1
if __name__ == '__main__':
solve() |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Standard_ML | Standard ML | OS.FileSys.remove "input.txt";
OS.FileSys.remove "/input.txt";
OS.FileSys.rmDir "docs";
OS.FileSys.rmDir "/docs"; |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Stata | Stata | erase input.txt
rmdir docs |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Tcl | Tcl | file delete input.txt /input.txt
# preserve directory if non-empty
file delete docs /docs
# delete even if non-empty
file delete -force docs /docs |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PL.2FSQL | PL/SQL | FUNCTION IsNumeric( VALUE IN VARCHAR2 )
RETURN BOOLEAN
IS
help NUMBER;
BEGIN
help := TO_NUMBER( VALUE );
RETURN( TRUE );
EXCEPTION
WHEN OTHERS THEN
RETURN( FALSE );
END; |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Plain_English | Plain English | To run:
Start up.
Show whether "cat" is numeric.
Show whether "3" is numeric.
Show whether "+3" is numeric.
Show whether "-123" is numeric.
Show whether "123,456" is numeric.
Show whether "11/5" is numeric.
Show whether "-26-1/3" is numeric.
Show whether "+26-1/3" is numeric.
Show whether "1/0" is numeric. \in Plain English, 1/0 is 0. Don't tell the mathematicians!
Show whether "3.14159" is numeric. \floating point is not implemented in Plain English.
Wait for the escape key.
Shut down.
To show whether a string is numeric:
Write the string then " -> " on the console without advancing.
If the string is any numeric literal, write "yes" on the console; exit.
Write "no" on the console. |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #RPL | RPL | <<
[ 1 3 -5 ]
[ 4 -2 -1 ]
DOT
>> |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Ruby | Ruby | irb(main):001:0> require 'matrix'
=> true
irb(main):002:0> Vector[1, 3, -5].inner_product Vector[4, -2, -1]
=> 3 |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Quackery | Quackery | [ 2dup = iff
[ 2drop drop ] done
dip over swap over = iff
[ 2drop drop ] done
rot echo sp
swap echo sp
echo cr ] is fire ( pol san fir --> )
[ 2dup = iff 2drop done
12 over -
dip over swap -
dup 1 < iff
[ 2drop drop ] done
dup 7 > iff
[ 2drop drop ] done
fire ] is sanitation ( pol san --> )
[ 7 times
[ dup
i^ 1+ sanitation ]
drop ] is police ( pol --> )
[ cr ' [ 2 4 6 ]
witheach police ] is departments ( --> )
departments |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #R | R | allPermutations <- setNames(expand.grid(seq(2, 7, by = 2), 1:7, 1:7), c("Police", "Sanitation", "Fire"))
solution <- allPermutations[which(rowSums(allPermutations)==12 & apply(allPermutations, 1, function(x) !any(duplicated(x)))),]
solution <- solution[order(solution$Police, solution$Sanitation),]
row.names(solution) <- paste0("Solution #", seq_len(nrow(solution)), ":")
print(solution) |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Toka | Toka | needs shell
" docs" remove
" input.txt" remove |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
- delete file
SET status = DELETE ("input.txt")
- delete directory
SET status = DELETE ("docs",-std-)
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #UNIX_Shell | UNIX Shell | rm -rf docs
rm input.txt
rm -rf /docs
rm /input.txt |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PowerShell | PowerShell | function isNumeric ($x) {
try {
0 + $x | Out-Null
return $true
} catch {
return $false
}
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Prolog | Prolog | numeric_string(String) :-
atom_string(Atom, String),
atom_number(Atom, _). |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Run_BASIC | Run BASIC | v1$ = "1, 3, -5"
v2$ = "4, -2, -1"
print "DotProduct of ";v1$;" and "; v2$;" is ";dotProduct(v1$,v2$)
end
function dotProduct(a$, b$)
while word$(a$,i + 1,",") <> ""
i = i + 1
v1$=word$(a$,i,",")
v2$=word$(b$,i,",")
dotProduct = dotProduct + val(v1$) * val(v2$)
wend
end function |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Rust | Rust | // alternatively, fn dot_product(a: &Vec<u32>, b: &Vec<u32>)
// but using slices is more general and rustic
fn dot_product(a: &[i32], b: &[i32]) -> Option<i32> {
if a.len() != b.len() { return None }
Some(
a.iter()
.zip( b.iter() )
.fold(0, |sum, (el_a, el_b)| sum + el_a*el_b)
)
}
fn main() {
let v1 = vec![1, 3, -5];
let v2 = vec![4, -2, -1];
println!("{}", dot_product(&v1, &v2).unwrap());
} |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Racket | Racket | #lang racket
(cons '(police fire sanitation)
(filter (λ (pfs) (and (not (check-duplicates pfs))
(= 12 (apply + pfs))
pfs))
(cartesian-product (range 2 8 2) (range 1 8) (range 1 8))))
|
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Raku | Raku | for (1..7).combinations(3).grep(*.sum == 12) {
for .permutations\ .grep(*.[0] %% 2) {
say <police fire sanitation> Z=> .list;
}
}
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Ursa | Ursa | decl file f
f.delete "input.txt"
f.delete "docs"
f.delete "/input.txt"
f.delete "/docs" |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #VAX_Assembly | VAX Assembly | 74 75 70 6E 69 20 65 74 65 6C 65 64 0000 1 dcl: .ascii "delete input.txt;,docs.dir;"
64 2E 73 63 6F 64 2C 3B 74 78 74 2E 000C
3B 72 69 0018
69 76 65 64 73 79 73 24 73 79 73 2C 001B 2 .ascii ",sys$sysdevice:[000000]input.txt;"
69 5D 30 30 30 30 30 30 5B 3A 65 63 0027
3B 74 78 74 2E 74 75 70 6E 0033
69 76 65 64 73 79 73 24 73 79 73 2C 003C 3 .ascii ",sys$sysdevice:[000000]docs.dir;"
64 5D 30 30 30 30 30 30 5B 3A 65 63 0048
3B 72 69 64 2E 73 63 6F 0054
005C 4
0000005C 005C 5 desc: .long .-dcl ;character count
00000000' 0060 6 .address dcl
0064 7
0000 0064 8 .entry main,0
F3 AF 7F 0066 9 pushaq desc
00000000'GF 01 FB 0069 10 calls #1, g^lib$do_command ;execute shell command
04 0070 11 ret
0071 12 .end main
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #VBA | VBA | Option Explicit
Sub DeleteFileOrDirectory()
Dim myPath As String
myPath = "C:\Users\surname.name\Desktop\Docs"
'delete file
Kill myPath & "\input.txt"
'delete Directory
RmDir myPath
End Sub |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PureBasic | PureBasic | Procedure IsNumeric(InString.s, DecimalCharacter.c = '.')
#NotNumeric = #False
#IsNumeric = #True
InString = Trim(InString)
Protected IsDecimal, CaughtDecimal, CaughtE
Protected IsSignPresent, IsSignAllowed = #True, CountNumeric
Protected *CurrentChar.Character = @InString
While *CurrentChar\c
Select *CurrentChar\c
Case '0' To '9'
CountNumeric + 1
IsSignAllowed = #False
Case DecimalCharacter
If CaughtDecimal Or CaughtE Or CountNumeric = 0
ProcedureReturn #NotNumeric
EndIf
CountNumeric = 0
CaughtDecimal = #True
IsDecimal = #True
Case '-', '+'
If IsSignPresent Or Not IsSignAllowed: ProcedureReturn #NotNumeric: EndIf
IsSignPresent = #True
Case 'E', 'e'
If CaughtE Or CountNumeric = 0
ProcedureReturn #NotNumeric
EndIf
CaughtE = #True
CountNumeric = 0
CaughtDecimal = #False
IsSignPresent = #False
IsSignAllowed = #True
Default
ProcedureReturn #NotNumeric
EndSelect
*CurrentChar + SizeOf(Character)
Wend
If CountNumeric = 0: ProcedureReturn #NotNumeric: EndIf
ProcedureReturn #IsNumeric
EndProcedure
If OpenConsole()
PrintN("'+3183.31151E+321' = " + Str(IsNumeric("+3183.31151E+321")))
PrintN("'-123456789' = " + Str(IsNumeric("-123456789")))
PrintN("'123.45.6789+' = " + Str(IsNumeric("123.45.6789+")))
PrintN("'-e' = " + Str(IsNumeric("-e")))
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #S-lang | S-lang | print(sum([1, 3, -5] * [4, -2, -1])); |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Sather | Sather | class MAIN is
main is
x ::= #VEC(|1.0, 3.0, -5.0|);
y ::= #VEC(|4.0, -2.0, -1.0|);
#OUT + x.dot(y) + "\n";
end;
end; |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #REXX | REXX | /*REXX program finds/displays all possible variants of (3) department numbering puzzle.*/
say 'police sanitation fire' /*display simple title for the output*/
say '══════ ══════════ ════' /* " head separator " " " */
#=0 /*number of solutions found (so far). */
do p=1 for 7; if p//2 then iterate /*try numbers for the police department*/
do s=1 for 7; if s==p then iterate /* " " " " fire " */
do f=1 for 7; if f==s then iterate /* " " " " sanitation " */
if p + s + f \== 12 then iterate /*check if sum of department nums ¬= 12*/
#= # + 1 /*bump count of the number of solutions*/
say center(p,6) center(s,10) center(f,4) /*display one possible solution. */
end /*s*/
end /*f*/
end /*p*/
say '══════ ══════════ ════' /* " head separator " " " */
say /*stick a fork in it, we're all done. */
say # ' solutions found.' /*also, show the # of solutions found. */ |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #VBScript | VBScript | Set oFSO = CreateObject( "Scripting.FileSystemObject" )
oFSO.DeleteFile "input.txt"
oFSO.DeleteFolder "docs"
oFSO.DeleteFile "\input.txt"
oFSO.DeleteFolder "\docs"
'Using Delete on file and folder objects
dim fil, fld
set fil = oFSO.GetFile( "input.txt" )
fil.Delete
set fld = oFSO.GetFolder( "docs" )
fld.Delete
set fil = oFSO.GetFile( "\input.txt" )
fil.Delete
set fld = oFSO.GetFolder( "\docs" )
fld.Delete
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Vedit_macro_language | Vedit macro language | // In current directory
File_Delete("input.txt", OK)
File_Rmdir("docs")
// In the root directory
File_Delete("/input.txt", OK)
File_Rmdir("/docs") |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Python | Python | def is_numeric(s):
try:
float(s)
return True
except (ValueError, TypeError):
return False
is_numeric('123.0') |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Quackery | Quackery | [ char . over find
tuck over found iff
[ swap pluck drop ]
else nip ] is -point ( $ --> $ )
[ -point $->n nip ] is numeric ( $ --> b )
[ dup echo$ say " is"
numeric not if say " not"
say " a valid number." cr ] is task ( $ --> )
$ "152" task
$ "-3.1415926" task
$ "Foo123" task |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.