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/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #C.23 | C# | using System;
using System.Text;
namespace Language_name_in_3D_ascii
{
public class F5
{
char[] z = { ' ', ' ', '_', '/', };
long[,] f ={
{87381,87381,87381,87381,87381,87381,87381,},
{349525,375733,742837,742837,375733,349525,349525,},
{742741,768853,742837,742837,768853,349525,349525,},
{349525,375733,742741,742741,375733,349525,349525,},
{349621,375733,742837,742837,375733,349525,349525,},
{349525,375637,768949,742741,375733,349525,349525,},
{351157,374101,768949,374101,374101,349525,349525,},
{349525,375733,742837,742837,375733,349621,351157,},
{742741,768853,742837,742837,742837,349525,349525,},
{181,85,181,181,181,85,85,},
{1461,1365,1461,1461,1461,1461,2901,},
{742741,744277,767317,744277,742837,349525,349525,},
{181,181,181,181,181,85,85,},
{1431655765,3149249365L,3042661813L,3042661813L,3042661813L,1431655765,1431655765,},
{349525,768853,742837,742837,742837,349525,349525,},
{349525,375637,742837,742837,375637,349525,349525,},
{349525,768853,742837,742837,768853,742741,742741,},
{349525,375733,742837,742837,375733,349621,349621,},
{349525,744373,767317,742741,742741,349525,349525,},
{349525,375733,767317,351157,768853,349525,349525,},
{374101,768949,374101,374101,351157,349525,349525,},
{349525,742837,742837,742837,375733,349525,349525,},
{5592405,11883957,11883957,5987157,5616981,5592405,5592405,},
{366503875925L,778827027893L,778827027893L,392374737749L,368114513237L,366503875925L,366503875925L,},
{349525,742837,375637,742837,742837,349525,349525,},
{349525,742837,742837,742837,375733,349621,375637,},
{349525,768949,351061,374101,768949,349525,349525,},
{375637,742837,768949,742837,742837,349525,349525,},
{768853,742837,768853,742837,768853,349525,349525,},
{375733,742741,742741,742741,375733,349525,349525,},
{192213,185709,185709,185709,192213,87381,87381,},
{1817525,1791317,1817429,1791317,1817525,1398101,1398101,},
{768949,742741,768853,742741,742741,349525,349525,},
{375733,742741,744373,742837,375733,349525,349525,},
{742837,742837,768949,742837,742837,349525,349525,},
{48053,23381,23381,23381,48053,21845,21845,},
{349621,349621,349621,742837,375637,349525,349525,},
{742837,744277,767317,744277,742837,349525,349525,},
{742741,742741,742741,742741,768949,349525,349525,},
{11883957,12278709,11908533,11883957,11883957,5592405,5592405,},
{11883957,12277173,11908533,11885493,11883957,5592405,5592405,},
{375637,742837,742837,742837,375637,349525,349525,},
{768853,742837,768853,742741,742741,349525,349525,},
{6010197,11885397,11909973,11885397,6010293,5592405,5592405,},
{768853,742837,768853,742837,742837,349525,349525,},
{375733,742741,375637,349621,768853,349525,349525,},
{12303285,5616981,5616981,5616981,5616981,5592405,5592405,},
{742837,742837,742837,742837,375637,349525,349525,},
{11883957,11883957,11883957,5987157,5616981,5592405,5592405,},
{3042268597L,3042268597L,3042661813L,1532713813,1437971797,1431655765,1431655765,},
{11883957,5987157,5616981,5987157,11883957,5592405,5592405,},
{11883957,5987157,5616981,5616981,5616981,5592405,5592405,},
{12303285,5593941,5616981,5985621,12303285,5592405,5592405,}
};
private F5(string s)
{
StringBuilder[] o = new StringBuilder[7];
for (int i = 0; i < 7; i++) o[i] = new StringBuilder();
for (int i = 0, l = s.Length; i < l; i++)
{
int c = s[i];
if (65 <= c && c <= 90) c -= 39;
else if (97 <= c && c <= 122) c -= 97;
else c = -1;
long[] d = new long[7];
Buffer.BlockCopy(f, (++c * sizeof(long) * 7), d, 0, 7 * sizeof(long));
for (int j = 0; j < 7; j++)
{
StringBuilder b = new StringBuilder();
long v = d[j];
while (v > 0)
{
b.Append(z[(int)(v & 3)]);
v >>= 2;
}
char[] charArray = b.ToString().ToCharArray();
Array.Reverse(charArray);
o[j].Append(new string(charArray));
}
}
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 7 - i; j++)
System.Console.Write(' ');
System.Console.WriteLine(o[i]);
}
}
public static void Main(string[] args)
{
new F5(args.Length > 0 ? args[0] : "C sharp");
}
}
} |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Yabasic | Yabasic | open "output.txt" for writing as #1
print #1 "This is a string"
close #1 |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #zkl | zkl | // write returns bytes written, GC will close the file (eventually)
File("foo","wb").write("this is a test",1,2,3); //-->17
f:=File("bar",wb");
data.pump(f,g); // use g to process data as it is written to file
f.close(); // don't wait for GC |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #360_Assembly | 360 Assembly | * Word wrap 29/01/2017
WORDWRAP CSECT
USING WORDWRAP,R13
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) " ->
LR R13,R15 " addressability
MVC S2,=CL96' ' s2=''
SR R0,R0
STH R0,LENS2 lens2=0
LA R8,1 i=1
LOOPI CH R8,=AL2(NTS) do i=1 to hbound(ts)
BH ELOOPI --
LH R4,LENS2
LTR R4,R4 if lens2=0
BNZ IFLENS2 then
LR R1,R8 i
MH R1,=H'48'
LA R14,TS-48(R1)
MVC S(48),0(R14) s=ts(i)
MVC S+48(48),=CL48' '
LA R12,L'TS jmax=length(ts)
B EIFLENS2 else
IFLENS2 MVC S,=CL96' ' s=''
LA R6,S @s
LH R7,LENS2
LA R4,S2 @s2
LH R5,LENS2
MVCL R6,R4 substr(s,1,lens2)=substr(s2,1,lens2)
LH R2,LENS2
LA R2,1(R2) lens2+1
LR R1,R8 i
MH R1,=H'48'
LA R14,TS-48(R1) @ts(i)
LA R15,S-1
AR R15,R2
MVC 0(48,R15),0(R14) substr(s,lens2+1,48)=ts(i)
LA R12,L'S jmax=length(s)
EIFLENS2 MVI OKS2,X'01' oks2=true
WHILEOK CLI OKS2,X'01' do while(oks2)
BNE EWHILEOK --
LR R9,R12 j=jmax /*loop1*/
LOOPJ1 CH R9,=H'1' do j=jmax to 1 by -1
BL ELOOPJ1 --
LA R14,S-1 @s-1
AR R14,R9 j
MVC CJ(1),0(R14) cj=substr(s,j,1)
CLI CJ,C' ' if cj^=' '
BNE ELOOPJ1 then leave j
BCTR R9,0 j=j-1
B LOOPJ1 end do j
ELOOPJ1 STH R9,LENS lens=j {length of s}
MVI OKJ,X'00' okj=false /*loop2*/
LH R11,W js=w
LH R4,W
CH R4,LENS if w>lens
BNH IFWLENS
LH R11,LENS js=lens
IFWLENS LR R9,R11 j=js
LOOPJ2 CH R9,=H'1' do j=js to 1 by -1
BL ELOOPJ2 --
LA R14,S-1 @s-1
AR R14,R9 +j
MVC CJ(1),0(R14) cj=substr(s,j,1)
CLI CJ,C' ' if cj=' '
BNE ITERJ2 then
MVI OKJ,X'01' okj=true
B ELOOPJ2 leave j
ITERJ2 BCTR R9,0 j=j-1
B LOOPJ2 end do j
ELOOPJ2 CLI OKJ,X'00' if ^okj
BNE ELOOPK
MVI OKK,X'00' okk=false /*loop3*/
LH R10,W k=w
LOOPK CH R10,LENS do k=w to lens
BH ELOOPK --
LA R14,S-1 @s-1
AR R14,R10 +k
MVC CK(1),0(R14) ck=substr(s,k,1)
CLI CK,C' ' if ck=' '
BNE ITERK then
MVI OKK,X'01' okk=true
B ELOOPK leave k
ITERK LA R10,1(R10) k=k+1
B LOOPK end do k
ELOOPK MVC S2,=CL96' ' s2=' '
SR R0,R0
STH R0,LENS2 lens2=0
MVI CAS,X'01' cas=true
LH R1,LENS
CH R1,W lens<w
BL IFLENSLW
MVI CAS,X'00' cas=false
IFLENSLW CLI CAS,X'00' if ^cas
BNE IFNOTCAS then
CLI OKJ,X'01' if okj
BNE NOKJ then
STH R9,LENS1 lens1=j
LH R2,LENS
SR R2,R9 -j
LA R2,1(R2)
STH R2,LENS2 lens2=lens-j+1
LA R6,S1
LR R7,R9 j
LA R4,S
LR R5,R7
MVCL R6,R4 s1=substr(s,1,j)
LH R4,LENS2
LTR R4,R4 if lens2>0
BNP ELJLENS2 then
LA R6,S2
LH R7,LENS2
LA R4,S(R9) @s(j+1)
LR R5,R7
MVCL R6,R4 s2=substr(s,j+1,lens2)
B EFJLENS2
ELJLENS2 SR R0,R0 else
STH R0,LENS2 lens2=0
EFJLENS2 B IFNOTCAS
NOKJ CLI OKK,X'01' else if okk
BNE NOTOKK
STH R10,LENS1 lens1=k
LH R2,LENS
SR R2,R10 -k
LA R2,1(R2)
STH R2,LENS2 lens2=lens-k+1
LA R6,S1
LR R7,R10 k
LA R4,S
LR R5,R7
MVCL R6,R4 s1=substr(s,1,k)
LH R4,LENS2
LTR R4,R4 if lens2>0
BNP ELKLENS2 then
LA R6,S2
LH R7,LENS2
LA R4,S(R10) @s(k+1)
LR R5,R7
MVCL R6,R4 s2=substr(s,k+1,lens2)
B EFKLENS2 else
ELKLENS2 SR R0,R0
STH R0,LENS2 lens2=0
EFKLENS2 B IFNOTCAS else
NOTOKK LH R0,LENS
STH R0,LENS1 lens1=lens
MVC S1,S s1=s
IFNOTCAS CLI CAS,X'01' if cas
BNE ELCAS then
LH R7,LENS
LA R7,1(R7)
LA R6,S2
LA R4,S
LR R5,R7
MVCL R6,R4 s2=substr(s,1,lens+1)
LH R2,LENS
LA R2,1(R2)
STH R2,LENS2 lens2=lens+1
B EFCAS else
ELCAS LA R6,PG
LA R7,L'PG
LA R4,S1
LH R5,LENS1
ICM R5,B'1000',=C' ' padding
MVCL R6,R4 pg=substr(s1,1,lens1)
XPRNT PG,L'PG put skip list(pg)
EFCAS MVI OKS2,X'00' oks2=false
LH R4,LENS2
CH R4,W if lens2>w
BNH EFWLENS2 then
MVI OKS2,X'01' oks2=true
LH R0,LENS2
STH R0,LENS lens=lens2
MVC S,S2 s=s2
EFWLENS2 B WHILEOK end while
EWHILEOK LA R8,1(R8) i=i+1
B LOOPI end do i
ELOOPI LH R4,LENS2
LTR R4,R4 if lens2^=0
BZ EFLENS2N then
LA R6,PG
LA R7,L'PG
LA R4,S2
LH R5,LENS2
ICM R5,B'1000',=C' ' padding
MVCL R6,R4 pg=substr(s2,1,lens2)
XPRNT PG,L'PG put skip list(pg)
EFLENS2N L R13,4(0,R13) epilog
LM R14,R12,12(R13) " restore
XR R15,R15 " rc=0
BR R14 exit
TS DC CL48'In olden times when wishing still helped one,'
DC CL48'there lived a king whose daughters were all,'
DC CL48'beautiful, but the youngest was so beautiful'
DC CL48'that the sun itself, which has seen so much,'
DC CL48'was astonished whenever it shone in her face.'
DC CL48'Close by the king''s castle lay a great dark'
DC CL48'forest, and under an old lime tree in the'
DC CL48'forest was a well, and when the day was very'
DC CL48'warm, the king''s child went out into the forest'
DC CL48'and sat down by the side of the cool fountain,'
DC CL48'and when she was bored she took a golden ball,'
DC CL48'and threw it up on high and caught it, and this'
DC CL48'ball was her favorite plaything.'
TSE DC 0C
NTS EQU (TSE-TS)/L'TS
W DC H'36' <-- input width 12<=w<=80
LENS DS H
S DS CL96
LENS1 DS H
S1 DS CL96
LENS2 DS H
S2 DS CL96
OKJ DS X
OKK DS X
OKS2 DS X
CAS DS X
CJ DS CL1
CK DS CL1
PG DS CL80
YREGS
END WORDWRAP |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.2B.2B | C++ | #include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using word_map = std::map<size_t, std::vector<std::string>>;
// Returns true if strings s1 and s2 differ by one character.
bool one_away(const std::string& s1, const std::string& s2) {
if (s1.size() != s2.size())
return false;
bool result = false;
for (size_t i = 0, n = s1.size(); i != n; ++i) {
if (s1[i] != s2[i]) {
if (result)
return false;
result = true;
}
}
return result;
}
// Join a sequence of strings into a single string using the given separator.
template <typename iterator_type, typename separator_type>
std::string join(iterator_type begin, iterator_type end,
separator_type separator) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += separator;
result += *begin;
}
}
return result;
}
// If possible, print the shortest chain of single-character modifications that
// leads from "from" to "to", with each intermediate step being a valid word.
// This is an application of breadth-first search.
bool word_ladder(const word_map& words, const std::string& from,
const std::string& to) {
auto w = words.find(from.size());
if (w != words.end()) {
auto poss = w->second;
std::vector<std::vector<std::string>> queue{{from}};
while (!queue.empty()) {
auto curr = queue.front();
queue.erase(queue.begin());
for (auto i = poss.begin(); i != poss.end();) {
if (!one_away(*i, curr.back())) {
++i;
continue;
}
if (to == *i) {
curr.push_back(to);
std::cout << join(curr.begin(), curr.end(), " -> ") << '\n';
return true;
}
std::vector<std::string> temp(curr);
temp.push_back(*i);
queue.push_back(std::move(temp));
i = poss.erase(i);
}
}
}
std::cout << from << " into " << to << " cannot be done.\n";
return false;
}
int main() {
word_map words;
std::ifstream in("unixdict.txt");
if (!in) {
std::cerr << "Cannot open file unixdict.txt.\n";
return EXIT_FAILURE;
}
std::string word;
while (getline(in, word))
words[word.size()].push_back(word);
word_ladder(words, "boy", "man");
word_ladder(words, "girl", "lady");
word_ladder(words, "john", "jane");
word_ladder(words, "child", "adult");
word_ladder(words, "cat", "dog");
word_ladder(words, "lead", "gold");
word_ladder(words, "white", "black");
word_ladder(words, "bubble", "tickle");
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the wheel or grid. Usually there will be a minimum word length of 3 or 4
characters. Each letter may only be used as many times as it appears in the wheel
or grid.
An example
N
D
E
O
K
G
E
L
W
Task
Write a program to solve the above "word wheel" puzzle.
Specifically:
Find all words of 3 or more letters using only the letters in the string ndeokgelw.
All words must contain the central letter K.
Each letter may be used only as many times as it appears in the string.
For this task we'll use lowercase English letters exclusively.
A "word" is defined to be any string contained in the file located at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt.
If you prefer to use a different dictionary, please state which one you have used.
Optional extra
Word wheel puzzles usually state that there is at least one nine-letter word to be found.
Using the above dictionary, find the 3x3 grids with at least one nine-letter
solution that generate the largest number of words of three or more letters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C | C | #include <stdbool.h>
#include <stdio.h>
#define MAX_WORD 80
#define LETTERS 26
bool is_letter(char c) { return c >= 'a' && c <= 'z'; }
int index(char c) { return c - 'a'; }
void word_wheel(const char* letters, char central, int min_length, FILE* dict) {
int max_count[LETTERS] = { 0 };
for (const char* p = letters; *p; ++p) {
char c = *p;
if (is_letter(c))
++max_count[index(c)];
}
char word[MAX_WORD + 1] = { 0 };
while (fgets(word, MAX_WORD, dict)) {
int count[LETTERS] = { 0 };
for (const char* p = word; *p; ++p) {
char c = *p;
if (c == '\n') {
if (p >= word + min_length && count[index(central)] > 0)
printf("%s", word);
} else if (is_letter(c)) {
int i = index(c);
if (++count[i] > max_count[i]) {
break;
}
} else {
break;
}
}
}
}
int main(int argc, char** argv) {
const char* dict = argc == 2 ? argv[1] : "unixdict.txt";
FILE* in = fopen(dict, "r");
if (in == NULL) {
perror(dict);
return 1;
}
word_wheel("ndeokgelw", 'k', 3, in);
fclose(in);
return 0;
} |
http://rosettacode.org/wiki/Wordiff | Wordiff | Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from
the last by a change in one letter.
The change can be either:
a deletion of one letter;
addition of one letter;
or change in one letter.
Note:
All words must be in the dictionary.
No word in a game can be repeated.
The first word must be three or four letters long.
Task
Create a program to aid in the playing of the game by:
Asking for contestants names.
Choosing an initial random three or four letter word from the dictionary.
Asking each contestant in their turn for a wordiff word.
Checking the wordiff word is:
in the dictionary,
not a repetition of past words,
and differs from the last appropriately.
Optional stretch goals
Add timing.
Allow players to set a maximum playing time for the game.
An internal timer accumulates how long each user takes to respond in their turns.
Play is halted if the maximum playing time is exceeded on a players input.
That last player must have entered a wordiff or loses.
If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds.
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
| #Vlang | Vlang | import os
import rand
import time
import arrays
fn is_wordiff(guesses []string, word string, dict []string) bool {
if word !in dict {
println('That word is not in the dictionary')
return false
}
if word in guesses {
println('That word has already been used')
return false
}
if word.len < guesses[guesses.len-1].len {
return is_wordiff_removal(word, guesses[guesses.len-1])
} else if word.len > guesses[guesses.len-1].len {
return is_wordiff_insertion(word, guesses[guesses.len-1])
}
return is_wordiff_change(word,guesses[guesses.len-1])
}
fn is_wordiff_removal(new_word string, last_word string) bool {
for i in 0..last_word.len {
if new_word == last_word[..i] + last_word[i+1..] {
return true
}
}
println('Word is not derived from previous by removal of one letter')
return false
}
fn is_wordiff_insertion(new_word string, last_word string) bool {
if new_word.len > last_word.len+1 {
println('More than one character insertion difference')
return false
}
mut a := new_word.split('')
b := last_word.split('')
for c in b {
idx := a.index(c)
if idx >=0 {
a.delete(idx)
}
}
if a.len >1 {
println('Word is not derived from previous by insertion of one letter')
return false
}
return true
}
fn is_wordiff_change(new_word string, last_word string) bool {
mut diff:=0
for i,c in new_word {
if c != last_word[i] {
diff++
}
}
if diff != 1 {
println('More or less than exactly one character changed')
return false
}
return true
}
fn main() {
words := os.read_lines('unixdict.txt')?
time_limit := os.input('Time limit (sec) or 0 for none: ').int()
players := os.input('Please enter player names, separated by commas: ').split(',')
dic_3_4 := words.filter(it.len in [3,4])
mut wordiffs := rand.choose<string>(dic_3_4,1)?
mut timing := [][]f64{len: players.len}
start := time.now()
mut turn_count := 0
for {
turn_start := time.now()
word := os.input('${players[turn_count%players.len]}: Input a wordiff from ${wordiffs[wordiffs.len-1]}: ')
if time_limit != 0.0 && time.since(start).seconds()>time_limit{
println('TIMES UP ${players[turn_count%players.len]}')
break
} else {
if is_wordiff(wordiffs, word, words) {
wordiffs<<word
}else{
timing[turn_count%players.len] << time.since(turn_start).seconds()
println('YOU HAVE LOST ${players[turn_count%players.len]}')
break
}
}
timing[turn_count%players.len] << time.since(turn_start).seconds()
turn_count++
}
println('Timing ranks:')
for i,p in timing {
sum := arrays.sum<f64>(p) or {0}
println(' ${players[i]}: ${sum/p.len:10.3 f} seconds average')
}
}
|
http://rosettacode.org/wiki/Wordiff | Wordiff | Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from
the last by a change in one letter.
The change can be either:
a deletion of one letter;
addition of one letter;
or change in one letter.
Note:
All words must be in the dictionary.
No word in a game can be repeated.
The first word must be three or four letters long.
Task
Create a program to aid in the playing of the game by:
Asking for contestants names.
Choosing an initial random three or four letter word from the dictionary.
Asking each contestant in their turn for a wordiff word.
Checking the wordiff word is:
in the dictionary,
not a repetition of past words,
and differs from the last appropriately.
Optional stretch goals
Add timing.
Allow players to set a maximum playing time for the game.
An internal timer accumulates how long each user takes to respond in their turns.
Play is halted if the maximum playing time is exceeded on a players input.
That last player must have entered a wordiff or loses.
If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Wren | Wren | import "random" for Random
import "/ioutil" for File, Input
import "/str" for Str
import "/sort" for Find
var rand = Random.new()
var words = File.read("unixdict.txt").trim().split("\n")
var player1 = Input.text("Player 1, please enter your name : ", 1)
var player2 = Input.text("Player 2, please enter your name : ", 1)
if (player2 == player1) player2 = player2 + "2"
var words3or4 = words.where { |w| w.count == 3 || w.count == 4 }.toList
var n = words3or4.count
var firstWord = words3or4[rand.int(n)]
var prevLen = firstWord.count
var prevWord = firstWord
var used = []
var player = player1
System.print("\nThe first word is %(firstWord)\n")
while (true) {
var word = Str.lower(Input.text("%(player), enter your word : ", 1))
var len = word.count
var ok = false
if (len < 3) {
System.print("Words must be at least 3 letters long.")
} else if (Find.first(words, word) == -1) {
System.print("Not in dictionary.")
} else if (used.contains(word)) {
System.print("Word has been used before.")
} else if (word == prevWord) {
System.print("You must change the previous word.")
} else if (len == prevLen) {
var changes = 0
for (i in 0...len) {
if (word[i] != prevWord[i]) {
changes = changes + 1
}
}
if (changes > 1) {
System.print("Only one letter can be changed.")
} else ok = true
} else if (len == prevLen + 1) {
var addition = false
var temp = word
for (i in 0...prevLen) {
if (word[i] != prevWord[i]) {
addition = true
temp = Str.delete(temp, i)
if (temp == prevWord) {
ok = true
}
break
}
}
if (!addition) ok = true
if (!ok) System.print("Invalid addition.")
} else if (len == prevLen - 1) {
var deletion = false
var temp = prevWord
for (i in 0...len) {
if (word[i] != prevWord[i]) {
deletion = true
temp = Str.delete(temp, i)
if (temp == word) {
ok = true
}
break
}
}
if (!deletion) ok = true
if (!ok) System.print("Invalid deletion.")
} else {
System.print("Invalid change.")
}
if (ok) {
prevLen = word.count
prevWord = word
used.add(word)
player = (player == player1) ? player2 : player1
} else {
System.print("So, sorry %(player), you've lost!")
return
}
} |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Java | Java | import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;
public class XiaolinWu extends JPanel {
public XiaolinWu() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
}
void plot(Graphics2D g, double x, double y, double c) {
g.setColor(new Color(0f, 0f, 0f, (float)c));
g.fillOval((int) x, (int) y, 2, 2);
}
int ipart(double x) {
return (int) x;
}
double fpart(double x) {
return x - floor(x);
}
double rfpart(double x) {
return 1.0 - fpart(x);
}
void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {
boolean steep = abs(y1 - y0) > abs(x1 - x0);
if (steep)
drawLine(g, y0, x0, y1, x1);
if (x0 > x1)
drawLine(g, x1, y1, x0, y0);
double dx = x1 - x0;
double dy = y1 - y0;
double gradient = dy / dx;
// handle first endpoint
double xend = round(x0);
double yend = y0 + gradient * (xend - x0);
double xgap = rfpart(x0 + 0.5);
double xpxl1 = xend; // this will be used in the main loop
double ypxl1 = ipart(yend);
if (steep) {
plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);
plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);
} else {
plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);
plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);
}
// first y-intersection for the main loop
double intery = yend + gradient;
// handle second endpoint
xend = round(x1);
yend = y1 + gradient * (xend - x1);
xgap = fpart(x1 + 0.5);
double xpxl2 = xend; // this will be used in the main loop
double ypxl2 = ipart(yend);
if (steep) {
plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);
plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);
} else {
plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);
plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);
}
// main loop
for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {
if (steep) {
plot(g, ipart(intery), x, rfpart(intery));
plot(g, ipart(intery) + 1, x, fpart(intery));
} else {
plot(g, x, ipart(intery), rfpart(intery));
plot(g, x, ipart(intery) + 1, fpart(intery));
}
intery = intery + gradient;
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
drawLine(g, 550, 170, 50, 435);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Xiaolin Wu's line algorithm");
f.setResizable(false);
f.add(new XiaolinWu(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #Delphi | Delphi |
//You need to use these units
uses
Classes,
Dialogs,
XMLIntf,
XMLDoc;
//..............................................
//This function creates the XML
function CreateXML(aNames, aRemarks: TStringList): string;
var
XMLDoc: IXMLDocument;
Root: IXMLNode;
i: Integer;
begin
//Input check
if (aNames = nil) or
(aRemarks = nil) then
begin
Result:= '<CharacterRemarks />';
Exit;
end;
//Creating the TXMLDocument instance
XMLDoc:= TXMLDocument.Create(nil);
//Activating the document
XMLDoc.Active:= True;
//Creating the Root element
Root:= XMLDoc.AddChild('CharacterRemarks');
//Creating the inner nodes
for i:=0 to Min(aNames.Count, aRemarks.Count) - 1 do
with Root.AddChild('Character') do
begin
Attributes['name']:= aNames[i];
Text:= aRemarks[i];
end;
//Outputting the XML as a string
Result:= XMLDoc.XML.Text;
end;
//..............................................
//Consuming code example (fragment)
var
Names,
Remarks: TStringList;
begin
//Creating the lists objects
Names:= TStringList.Create;
Remarks:= TStringList.Create;
try
//Filling the list with names
Names.Add('April');
Names.Add('Tam O''Shanter');
Names.Add('Emily');
//Filling the list with remarks
Remarks.Add('Bubbly: I''m > Tam and <= Emily');
Remarks.Add('Burns: "When chapman billies leave the street ..."');
Remarks.Add('Short & shrift');
//Constructing and showing the XML
Showmessage(CreateXML(Names, Remarks));
finally
//Freeing the list objects
Names.Free;
Remarks.Free;
end;
end;
|
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Common_Lisp | Common Lisp | (defparameter *xml-blob*
"<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />
<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />
<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">
<Pet Type=\"dog\" Name=\"Rover\" />
</Student>
<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />
</Students>")
(let* ((document (cxml:parse *xml-blob* (cxml-dom:make-dom-builder)))
(students (dom:item (dom:get-elements-by-tag-name document "Students") 0))
(student-names '()))
(dom:do-node-list (child (dom:child-nodes students) (nreverse student-names))
(when (dom:element-p child)
(push (dom:get-attribute child "Name") student-names)))) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Standard_ML | Standard ML |
(* create first array and assign elements *)
-val first = Array.tabulate (10,fn x=>x+10) ;
val first = fromList[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: int array
(* assign to array 'second' *)
-val second=first ;
val second = fromList[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: int array
(* retrieve 5th element *)
-Array.sub(second,4);
val it = 14: int
|
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams.
For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage.
Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.
A win is worth three points.
A draw/tie is worth one point.
A loss is worth zero points.
Task
Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them.
Calculate the standings points for each team with each combination of outcomes.
Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.
Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?".
Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.
| #Raku | Raku | constant scoring = 0, 1, 3;
my @histo = [0 xx 10] xx 4;
for [X] ^3 xx 6 -> @results {
my @s;
for @results Z (^4).combinations(2) -> ($r, @g) {
@s[@g[0]] += scoring[$r];
@s[@g[1]] += scoring[2 - $r];
}
for @histo Z @s.sort -> (@h, $v) {
++@h[$v];
}
}
say .fmt('%3d',' ') for @histo.reverse; |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #NewLISP | NewLISP | ; file: write-float-array.lsp
; url: http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
; author: oofoe 2012-01-30
; The "transpose" function is used to flip the joined lists around so
; that it's easier to iterate through them together.
(define (write-float-array x xp y yp filename)
(let ((f (format "%%-10.%dg %%-10.%dg" xp yp))
(o (open filename "write")))
(dolist (v (transpose (list x y)))
(write-line o (format f (v 0) (v 1))))
(close o)
))
; Test
(write-float-array
'(1 2 3 1e11) 3
'(1 1.4142135623730951 1.7320508075688772 316227.76601683791) 5
"filename.chan")
(println "File contents:")
(print (read-file "filename.chan"))
(exit) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Microsoft_Small_Basic | Microsoft Small Basic |
For offset = 1 To 100
For i = 0 To 100 Step offset
a[i] = a[i] + 1
EndFor
EndFor
' Print "opened" doors
For i = 1 To 100
If math.Remainder(a[i], 2) = 1 Then
TextWindow.WriteLine(i)
EndIf
EndFor
|
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Python | Python | from xml.dom.minidom import getDOMImplementation
dom = getDOMImplementation()
document = dom.createDocument(None, "root", None)
topElement = document.documentElement
firstElement = document.createElement("element")
topElement.appendChild(firstElement)
textNode = document.createTextNode("Some text here")
firstElement.appendChild(textNode)
xmlString = document.toprettyxml(" " * 4) |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Racket | Racket |
#lang at-exp racket
(require xml)
(define xml-str
@~a{<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>})
;; read & parse to get an xml value
(define xml (read-xml/document (open-input-string xml-str)))
;; print it out in xml form, which is identical to the input xml
(write-xml xml)
(newline)
|
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #C.2B.2B | C++ |
#include <windows.h>
#include <iostream>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
cout <<
" ______ ______ " << endl <<
" _____ _____|\\ \\ _____|\\ \\ " << endl <<
" _____\\ \\_ / / | | / / | |" << endl <<
" / /| || |/ /|| |/ /|" << endl <<
" / / /____/|| |\\____/ || |\\____/ |" << endl <<
"| | |____|/ |\\ \\ | / |\\ \\ | / " << endl <<
"| | _____ | \\ \\___|/ | \\ \\___|/ " << endl <<
"|\\ \\|\\ \\ | \\ \\ | \\ \\ " << endl <<
"| \\_____\\| | \\ \\_____\\ \\ \\_____\\ " << endl <<
"| | /____/| \\ | | \\ | | " << endl <<
" \\|_____| || \\|_____| \\|_____| " << endl <<
" |____|/ ";
cout << endl << endl << endl;
system( "pause" );
return 0;
}
//--------------------------------------------------------------------------------------------------
|
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may overlap but are not allowed to zigzag, or wrap around.
Task
Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.
The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message.
Pack a minimum of 25 words into the grid.
Print the resulting grid and the solutions.
Example
0 1 2 3 4 5 6 7 8 9
0 n a y r y R e l m f
1 y O r e t s g n a g
2 t n e d i S k y h E
3 n o t n c p c w t T
4 a l s u u n T m a x
5 r o k p a r i s h h
6 a A c f p a e a c C
7 u b u t t t O l u n
8 g y h w a D h p m u
9 m i r p E h o g a n
parish (3,5)(8,5) gangster (9,1)(2,1)
paucity (4,6)(4,0) guaranty (0,8)(0,1)
prim (3,9)(0,9) huckster (2,8)(2,1)
plasm (7,8)(7,4) fancy (3,6)(7,2)
hogan (5,9)(9,9) nolo (1,2)(1,5)
under (3,4)(3,0) chatham (8,6)(8,0)
ate (4,8)(6,6) nun (9,7)(9,9)
butt (1,7)(4,7) hawk (9,5)(6,2)
why (3,8)(1,8) ryan (3,0)(0,0)
fay (9,0)(7,2) much (8,8)(8,5)
tar (5,7)(5,5) elm (6,0)(8,0)
max (7,4)(9,4) pup (5,3)(3,5)
mph (8,8)(6,8)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | -V
dirs = [[1, 0], [ 0, 1], [ 1, 1],
[1, -1], [-1, 0],
[0, -1], [-1, -1], [-1, 1]]
n_rows = 10
n_cols = 10
grid_size = n_rows * n_cols
min_words = 25
T Grid
num_attempts = 0
[[String]] cells = [[‘’] * :n_cols] * :n_rows
[String] solutions
F read_words(filename)
[String] words
L(line) File(filename).read_lines()
V s = line.lowercase()
I re:‘^[a-z]{3,10}’.match(s)
words.append(s)
R words
F place_message(Grid &grid; =msg)
msg = msg.uppercase().replace(re:‘[^A-Z]’, ‘’)
V message_len = msg.len
I message_len C 0 <.< :grid_size
V gap_size = :grid_size I/ message_len
L(i) 0 .< message_len
V pos = i * gap_size + random:(0 .. gap_size)
grid.cells[pos I/ :n_cols][pos % :n_cols] = msg[i]
R message_len
R 0
F try_location(Grid &grid; word, direction, pos)
V r = pos I/ :n_cols
V c = pos % :n_cols
V length = word.len
I (:dirs[direction][0] == 1 & (length + c) > :n_cols) |
(:dirs[direction][0] == -1 & (length - 1) > c) |
(:dirs[direction][1] == 1 & (length + r) > :n_rows) |
(:dirs[direction][1] == -1 & (length - 1) > r)
R 0
V rr = r
V cc = c
V i = 0
V overlaps = 0
L i < length
I grid.cells[rr][cc] != ‘’ & grid.cells[rr][cc] != word[i]
R 0
cc += :dirs[direction][0]
rr += :dirs[direction][1]
i++
rr = r
cc = c
i = 0
L i < length
I grid.cells[rr][cc] == word[i]
overlaps++
E
grid.cells[rr][cc] = word[i]
I i < length - 1
cc += :dirs[direction][0]
rr += :dirs[direction][1]
i++
V letters_placed = length - overlaps
I letters_placed > 0
grid.solutions.append(‘#<10 (#.,#.)(#.,#.)’.format(word, c, r, cc, rr))
R letters_placed
F try_place_word(Grid &grid; word)
V rand_dir = random:(0 .. :dirs.len)
V rand_pos = random:(0 .. :grid_size)
L(=direction) 0 .< :dirs.len
direction = (direction + rand_dir) % :dirs.len
L(=pos) 0 .< :grid_size
pos = (pos + rand_pos) % :grid_size
V letters_placed = try_location(&grid, word, direction, pos)
I letters_placed > 0
R letters_placed
R 0
F create_word_search(&words)
V grid = Grid()
V num_attempts = 0
L num_attempts < 100
num_attempts++
random:shuffle(&words)
grid = Grid()
V message_len = place_message(&grid, ‘Rosetta Code’)
V target = :grid_size - message_len
V cells_filled = 0
L(word) words
cells_filled += try_place_word(&grid, word)
I cells_filled == target
I grid.solutions.len >= :min_words
grid.num_attempts = num_attempts
R grid
E
L.break
R grid
F print_result(grid)
I grid.num_attempts == 0
print(‘No grid to display’)
R
V size = grid.solutions.len
print(‘Attempts: #.’.format(grid.num_attempts))
print(‘Number of words: #.’.format(size))
print("\n 0 1 2 3 4 5 6 7 8 9\n")
L(r) 0 .< :n_rows
print(‘#. ’.format(r), end' ‘’)
L(c) 0 .< :n_cols
print(‘ #. ’.format(grid.cells[r][c]), end' ‘’)
print()
print()
L(i) (0 .< size - 1).step(2)
print(‘#. #.’.format(grid.solutions[i], grid.solutions[i + 1]))
I size % 2 == 1
print(grid.solutions[size - 1])
print_result(create_word_search(&read_words(‘unixdict.txt’))) |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #Action.21 | Action! | CHAR ARRAY text(1000)
CARD length
PROC AppendText(CHAR ARRAY part)
BYTE i
FOR i=1 TO part(0)
DO
text(length)=part(i)
length==+1
OD
RETURN
INT FUNC GetPosForWrap(BYTE lineLen INT start)
INT pos
pos=start+lineLen
IF pos>=length THEN
RETURN (length-1)
FI
WHILE pos>start AND text(pos)#32
DO
pos==-1
OD
IF pos=start THEN
pos=start+lineLen
ELSE
pos==-1
FI
RETURN (pos)
PROC PrintTextWrapped(BYTE lineLen)
INT i,pos
BYTE wrap,screenWidth=[40]
i=0
WHILE i<length
DO
pos=GetPosForWrap(lineLen,i)
IF pos-i=screenWidth-1 OR pos=length-1 THEN
wrap=0
ELSE
wrap=1
FI
WHILE i<=pos
DO
Put(text(i))
i==+1
OD
WHILE i<length AND text(i)=32
DO
i==+1
OD
IF wrap THEN
PutE()
FI
OD
RETURN
PROC Test(BYTE lineLen)
BYTE CH=$02FC
Put(125) ;clear screen
PrintF("Line length=%B%E%E",lineLen)
PrintTextWrapped(lineLen)
PrintF("%E%EPress any key to continue...")
DO UNTIL CH#$FF OD
CH=$FF
RETURN
PROC Main()
BYTE LMARGIN=$52,old
length=0
AppendText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. ")
AppendText("Maecenas varius sapien vel purus hendrerit vehicula. ")
AppendText("Integer hendrerit viverra turpis, ac sagittis arcu pharetra id. ")
AppendText("Sed dapibus enim non dui posuere sit amet rhoncus tellus consectetur. ")
AppendText("Proin blandit lacus vitae nibh tincidunt cursus. ")
AppendText("Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. ")
AppendText("Nam tincidunt purus at tortor tincidunt et aliquam dui gravida. ")
AppendText("Nulla consectetur sem vel felis vulputate et imperdiet orci pharetra. ")
AppendText("Nam vel tortor nisi. Sed eget porta tortor. ")
AppendText("Aliquam suscipit lacus vel odio faucibus tempor. ")
AppendText("Sed ipsum est, condimentum eget eleifend ac, ultricies non dui.")
old=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Test(40)
Test(30)
Test(20)
LMARGIN=old ;restore left margin on the screen
RETURN
|
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ada | Ada | generic
with procedure Put_Line(Line: String);
package Word_Wrap is
type Basic(Length_Of_Output_Line: Positive) is tagged private;
procedure Push_Word(State: in out Basic; Word: String);
procedure New_Paragraph(State: in out Basic);
procedure Finish(State: in out Basic);
private
type Basic(Length_Of_Output_Line: Positive) is tagged record
Line: String(1 .. Length_Of_Output_Line);
Size: Natural := 0; -- Line(1 .. Size) is relevant
Top_Of_Paragraph: Boolean := True;
end record;
end Word_Wrap; |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
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
| #F.23 | F# |
// Word ladder: Nigel Galloway. June 5th., 2021
let fG n g=n|>List.partition(fun n->2>Seq.fold2(fun z n g->z+if n=g then 0 else 1) 0 n g)
let wL n g=let dict=seq{use n=System.IO.File.OpenText("unixdict.txt") in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter(Seq.length>>(=)(Seq.length n))|>List.ofSeq|>List.except [n]
let (|Done|_|) n=n|>List.tryFind((=)g)
let rec wL n g l=match n with h::t->let i,e=fG l (List.head h) in match i with Done i->Some((i::h)|>List.rev) |_->wL t ((i|>List.map(fun i->i::h))@g) e
|_->match g with []->None |_->wL g [] l
let i,e=fG dict n in match i with Done i->Some([n;g]) |_->wL(i|>List.map(fun g->[g;n])) [] e
[("boy","man");("girl","lady");("john","jane");("child","adult")]|>List.iter(fun(n,g)->printfn "%s" (match wL n g with Some n->n|>String.concat " -> " |_->n+" into "+g+" can't be done"))
|
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the wheel or grid. Usually there will be a minimum word length of 3 or 4
characters. Each letter may only be used as many times as it appears in the wheel
or grid.
An example
N
D
E
O
K
G
E
L
W
Task
Write a program to solve the above "word wheel" puzzle.
Specifically:
Find all words of 3 or more letters using only the letters in the string ndeokgelw.
All words must contain the central letter K.
Each letter may be used only as many times as it appears in the string.
For this task we'll use lowercase English letters exclusively.
A "word" is defined to be any string contained in the file located at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt.
If you prefer to use a different dictionary, please state which one you have used.
Optional extra
Word wheel puzzles usually state that there is at least one nine-letter word to be found.
Using the above dictionary, find the 3x3 grids with at least one nine-letter
solution that generate the largest number of words of three or more letters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.2B.2B | C++ | #include <array>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
// A multiset specialized for strings consisting of lowercase
// letters ('a' to 'z').
class letterset {
public:
letterset() {
count_.fill(0);
}
explicit letterset(const std::string& str) {
count_.fill(0);
for (char c : str)
add(c);
}
bool contains(const letterset& set) const {
for (size_t i = 0; i < count_.size(); ++i) {
if (set.count_[i] > count_[i])
return false;
}
return true;
}
unsigned int count(char c) const {
return count_[index(c)];
}
bool is_valid() const {
return count_[0] == 0;
}
void add(char c) {
++count_[index(c)];
}
private:
static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }
static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }
// elements 1..26 contain the number of times each lowercase
// letter occurs in the word
// element 0 is the number of other characters in the word
std::array<unsigned int, 27> count_;
};
template <typename iterator, typename separator>
std::string join(iterator begin, iterator end, separator sep) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += sep;
result += *begin;
}
}
return result;
}
using dictionary = std::vector<std::pair<std::string, letterset>>;
dictionary load_dictionary(const std::string& filename, int min_length,
int max_length) {
std::ifstream in(filename);
if (!in)
throw std::runtime_error("Cannot open file " + filename);
std::string word;
dictionary result;
while (getline(in, word)) {
if (word.size() < min_length)
continue;
if (word.size() > max_length)
continue;
letterset set(word);
if (set.is_valid())
result.emplace_back(word, set);
}
return result;
}
void word_wheel(const dictionary& dict, const std::string& letters,
char central_letter) {
letterset set(letters);
if (central_letter == 0 && !letters.empty())
central_letter = letters.at(letters.size()/2);
std::map<size_t, std::vector<std::string>> words;
for (const auto& pair : dict) {
const auto& word = pair.first;
const auto& subset = pair.second;
if (subset.count(central_letter) > 0 && set.contains(subset))
words[word.size()].push_back(word);
}
size_t total = 0;
for (const auto& p : words) {
const auto& v = p.second;
auto n = v.size();
total += n;
std::cout << "Found " << n << " " << (n == 1 ? "word" : "words")
<< " of length " << p.first << ": "
<< join(v.begin(), v.end(), ", ") << '\n';
}
std::cout << "Number of words found: " << total << '\n';
}
void find_max_word_count(const dictionary& dict, int word_length) {
size_t max_count = 0;
std::vector<std::pair<std::string, char>> max_words;
for (const auto& pair : dict) {
const auto& word = pair.first;
if (word.size() != word_length)
continue;
const auto& set = pair.second;
dictionary subsets;
for (const auto& p : dict) {
if (set.contains(p.second))
subsets.push_back(p);
}
letterset done;
for (size_t index = 0; index < word_length; ++index) {
char central_letter = word[index];
if (done.count(central_letter) > 0)
continue;
done.add(central_letter);
size_t count = 0;
for (const auto& p : subsets) {
const auto& subset = p.second;
if (subset.count(central_letter) > 0)
++count;
}
if (count > max_count) {
max_words.clear();
max_count = count;
}
if (count == max_count)
max_words.emplace_back(word, central_letter);
}
}
std::cout << "Maximum word count: " << max_count << '\n';
std::cout << "Words of " << word_length << " letters producing this count:\n";
for (const auto& pair : max_words)
std::cout << pair.first << " with central letter " << pair.second << '\n';
}
constexpr const char* option_filename = "filename";
constexpr const char* option_wheel = "wheel";
constexpr const char* option_central = "central";
constexpr const char* option_min_length = "min-length";
constexpr const char* option_part2 = "part2";
int main(int argc, char** argv) {
const int word_length = 9;
int min_length = 3;
std::string letters = "ndeokgelw";
std::string filename = "unixdict.txt";
char central_letter = 0;
bool do_part2 = false;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
(option_filename, po::value<std::string>(), "name of dictionary file")
(option_wheel, po::value<std::string>(), "word wheel letters")
(option_central, po::value<char>(), "central letter (defaults to middle letter of word)")
(option_min_length, po::value<int>(), "minimum word length")
(option_part2, "include part 2");
try {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count(option_filename))
filename = vm[option_filename].as<std::string>();
if (vm.count(option_wheel))
letters = vm[option_wheel].as<std::string>();
if (vm.count(option_central))
central_letter = vm[option_central].as<char>();
if (vm.count(option_min_length))
min_length = vm[option_min_length].as<int>();
if (vm.count(option_part2))
do_part2 = true;
auto dict = load_dictionary(filename, min_length, word_length);
// part 1
word_wheel(dict, letters, central_letter);
// part 2
if (do_part2) {
std::cout << '\n';
find_max_word_count(dict, word_length);
}
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Julia | Julia | using Images
fpart(x) = mod(x, one(x))
rfpart(x) = one(x) - fpart(x)
function drawline!(img::Matrix{Gray{N0f8}}, x0::Integer, y0::Integer, x1::Integer, y1::Integer)
steep = abs(y1 - y0) > abs(x1 - x0)
if steep
x0, y0 = y0, x0
x1, y1 = y1, x1
end
if x0 > x1
x0, x1 = x1, x0
y0, y1 = y1, y0
end
dx = x1 - x0
dy = y1 - y0
grad = dy / dx
if iszero(dx)
grad = oftype(grad, 1.0)
end
# handle first endpoint
xend = round(Int, x0)
yend = y0 + grad * (xend - x0)
xgap = rfpart(x0 + 0.5)
xpxl1 = xend
ypxl1 = floor(Int, yend)
if steep
img[ypxl1, xpxl1] = rfpart(yend) * xgap
img[ypxl1+1, xpxl1] = fpart(yend) * xgap
else
img[xpxl1, ypxl1 ] = rfpart(yend) * xgap
img[xpxl1, ypxl1+1] = fpart(yend) * xgap
end
intery = yend + grad # first y-intersection for the main loop
# handle second endpoint
xend = round(Int, x1)
yend = y1 + grad * (xend - x1)
xgap = fpart(x1 + 0.5)
xpxl2 = xend
ypxl2 = floor(Int, yend)
if steep
img[ypxl2, xpxl2] = rfpart(yend) * xgap
img[ypxl2+1, xpxl2] = fpart(yend) * xgap
else
img[xpxl2, ypxl2 ] = rfpart(yend) * xgap
img[xpxl2, ypxl2+1] = fpart(yend) * xgap
end
# main loop
if steep
for x in xpxl1+1:xpxl2-1
img[floor(Int, intery), x] = rfpart(intery)
img[floor(Int, intery)+1, x] = fpart(intery)
intery += grad
end
else
for x in xpxl1+1:xpxl2-1
img[x, floor(Int, intery) ] = rfpart(intery)
img[x, floor(Int, intery)+1] = fpart(intery)
intery += grad
end
end
return img
end
img = fill(Gray(1.0N0f8), 250, 250);
drawline!(img, 8, 8, 192, 154) |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.*
import javax.swing.*
class XiaolinWu: JPanel() {
init {
preferredSize = Dimension(640, 640)
background = Color.white
}
private fun plot(g: Graphics2D, x: Double, y: Double, c: Double) {
g.color = Color(0f, 0f, 0f, c.toFloat())
g.fillOval(x.toInt(), y.toInt(), 2, 2)
}
private fun ipart(x: Double) = x.toInt()
private fun fpart(x: Double) = x - Math.floor(x)
private fun rfpart(x: Double) = 1.0 - fpart(x)
private fun drawLine(g: Graphics2D, x0: Double, y0: Double, x1: Double, y1: Double) {
val steep = Math.abs(y1 - y0) > Math.abs(x1 - x0)
if (steep) drawLine(g, y0, x0, y1, x1)
if (x0 > x1) drawLine(g, x1, y1, x0, y0)
val dx = x1 - x0
val dy = y1 - y0
val gradient = dy / dx
// handle first endpoint
var xend = Math.round(x0).toDouble()
var yend = y0 + gradient * (xend - x0)
var xgap = rfpart(x0 + 0.5)
val xpxl1 = xend // this will be used in the main loop
val ypxl1 = ipart(yend).toDouble()
if (steep) {
plot(g, ypxl1, xpxl1, rfpart(yend) * xgap)
plot(g, ypxl1 + 1.0, xpxl1, fpart(yend) * xgap)
}
else {
plot(g, xpxl1, ypxl1, rfpart(yend) * xgap)
plot(g, xpxl1, ypxl1 + 1.0, fpart(yend) * xgap)
}
// first y-intersection for the main loop
var intery = yend + gradient
// handle second endpoint
xend = Math.round(x1).toDouble()
yend = y1 + gradient * (xend - x1)
xgap = fpart(x1 + 0.5)
val xpxl2 = xend // this will be used in the main loop
val ypxl2 = ipart(yend).toDouble()
if (steep) {
plot(g, ypxl2, xpxl2, rfpart(yend) * xgap)
plot(g, ypxl2 + 1.0, xpxl2, fpart(yend) * xgap)
}
else {
plot(g, xpxl2, ypxl2, rfpart(yend) * xgap)
plot(g, xpxl2, ypxl2 + 1.0, fpart(yend) * xgap)
}
// main loop
var x = xpxl1 + 1.0
while (x <= xpxl2 - 1) {
if (steep) {
plot(g, ipart(intery).toDouble(), x, rfpart(intery))
plot(g, ipart(intery).toDouble() + 1.0, x, fpart(intery))
}
else {
plot(g, x, ipart(intery).toDouble(), rfpart(intery))
plot(g, x, ipart(intery).toDouble() + 1.0, fpart(intery))
}
intery += gradient
x++
}
}
override protected fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
drawLine(g, 550.0, 170.0, 50.0, 435.0)
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
f.title = "Xiaolin Wu's line algorithm"
f.isResizable = false
f.add(XiaolinWu(), BorderLayout.CENTER)
f.pack()
f.setLocationRelativeTo(null)
f.isVisible = true
}
} |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #Erlang | Erlang |
-module( xml_output ).
-export( [task/0] ).
-include_lib("xmerl/include/xmerl.hrl").
task() ->
Data = {'CharacterRemarks', [], [{'Character', [{name, X}], [[Y]]} || {X, Y} <- contents()]},
lists:flatten( xmerl:export_simple([Data], xmerl_xml) ).
contents() -> [{"April", "Bubbly: I'm > Tam and <= Emily"}, {"Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""}, {"Emily", "Short & shrift"}].
|
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #D | D | import kxml.xml;
char[]xmlinput =
"<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />
<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />
<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">
<Pet Type=\"dog\" Name=\"Rover\" />
</Student>
<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />
</Students>";
void main() {
auto root = readDocument(xmlinput);
foreach(students;root.getChildren) if (!students.isCData && students.getName == "Students") {
// now look for student subnodes
foreach(student;students.getChildren) if (!student.isCData && student.getName == "Student") {
// we found a student!
std.stdio.writefln("%s",student.getAttribute("Name"));
}
// we only want one, so break out of the loop once we find a match
break;
}
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Stata | Stata | matrix a = 2,9,4\7,5,3\6,1,8
display det(a)
matrix svd u d v = a
matrix b = u*diag(d)*v'
matrix list b
* store the u and v matrices in the current dataset
svmat u
svmat v |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams.
For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage.
Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.
A win is worth three points.
A draw/tie is worth one point.
A loss is worth zero points.
Task
Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them.
Calculate the standings points for each team with each combination of outcomes.
Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.
Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?".
Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.
| #REXX | REXX | /* REXX -------------------------------------------------------------------*/
results = '000000' /*start with left teams all losing */
games = '12 13 14 23 24 34'
points.=0
records.=0
Do Until nextResult(results)=0
records.=0
Do i=1 To 6
r=substr(results,i,1)
g=word(games,i); Parse Var g g1 +1 g2
Select
When r='2' Then /* win for left team */
records.g1=records.g1+3
When r='1' Then Do /* draw */
records.g1=records.g1+1
records.g2=records.g2+1
End
When r='0' Then /* win for right team */
records.g2=records.g2+3
End
End
Call sort_records /* sort ascending, */
/* first place team on the right */
r1=records.1
r2=records.2
r3=records.3
r4=records.4
points.0.r1=points.0.r1+1
points.1.r2=points.1.r2+1
points.2.r3=points.2.r3+1
points.3.r4=points.3.r4+1
End
ol.='['
sep=', '
Do i=0 To 9
If i=9 Then sep=']'
ol.0=ol.0||points.0.i||sep
ol.1=ol.1||points.1.i||sep
ol.2=ol.2||points.2.i||sep
ol.3=ol.3||points.3.i||sep
End
Say ol.3
Say ol.2
Say ol.1
Say ol.0
Exit
nextResult: Procedure Expose results
/* results is a string of 6 base 3 digits to which we add 1 */
/* e.g., '000212 +1 -> 000220 */
If results="222222" Then Return 0
res=0
do i=1 To 6
res=res*3+substr(results,i,1)
End
res=res+1
s=''
Do i=1 To 6
b=res//3
res=res%3
s=b||s
End
results=s
Return 1
sort_records: Procedure Expose records.
Do i=1 To 3
Do j=i+1 To 4
If records.j<records.i Then
Parse Value records.i records.j With records.j records.i
End
End
Return |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Nim | Nim | import strutils, math, sequtils
const OutFileName = "floatarr2file.txt"
const
XPrecision = 3
Yprecision = 5
let a = [1.0, 2.0, 3.0, 100_000_000_000.0]
let b = [sqrt(a[0]), sqrt(a[1]), sqrt(a[2]), sqrt(a[3])]
var res = ""
for t in zip(a, b):
res.add formatFloat(t[0], ffDefault, Xprecision) & " " &
formatFloat(t[1], ffDefault, Yprecision) & "\n"
OutFileName.writeFile res
var res2 = OutFileName.readFile()
echo res2 |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #OCaml | OCaml | let write_dat filename x y ?(xprec=3) ?(yprec=5) () =
let oc = open_out filename in
let write_line a b = Printf.fprintf oc "%.*g\t%.*g\n" xprec a yprec b in
List.iter2 write_line x y;
close_out oc |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #MiniScript | MiniScript | d = {}
for p in range(1, 100)
for t in range(p, 100, p)
if d.hasIndex(t) then d.remove t else d.push t
end for
end for
print d.indexes.sort |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Raku | Raku | use XML;
use XML::Writer;
say my $document = XML::Document.new(
XML::Writer.serialize( :root[ :element['Some text here', ], ] )
); |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Rascal | Rascal | import lang::xml::DOM;
public void main(){
x = document(element(none(), "root", [element(none(), "element", [charData("Some text here")])]));
return println(xmlPretty(x));
} |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #Clojure | Clojure | (use 'clj-figlet.core)
(println
(render-to-string
(load-flf "ftp://ftp.figlet.org/pub/figlet/fonts/contributed/larry3d.flf")
"Clojure")) |
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may overlap but are not allowed to zigzag, or wrap around.
Task
Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.
The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message.
Pack a minimum of 25 words into the grid.
Print the resulting grid and the solutions.
Example
0 1 2 3 4 5 6 7 8 9
0 n a y r y R e l m f
1 y O r e t s g n a g
2 t n e d i S k y h E
3 n o t n c p c w t T
4 a l s u u n T m a x
5 r o k p a r i s h h
6 a A c f p a e a c C
7 u b u t t t O l u n
8 g y h w a D h p m u
9 m i r p E h o g a n
parish (3,5)(8,5) gangster (9,1)(2,1)
paucity (4,6)(4,0) guaranty (0,8)(0,1)
prim (3,9)(0,9) huckster (2,8)(2,1)
plasm (7,8)(7,4) fancy (3,6)(7,2)
hogan (5,9)(9,9) nolo (1,2)(1,5)
under (3,4)(3,0) chatham (8,6)(8,0)
ate (4,8)(6,6) nun (9,7)(9,9)
butt (1,7)(4,7) hawk (9,5)(6,2)
why (3,8)(1,8) ryan (3,0)(0,0)
fay (9,0)(7,2) much (8,8)(8,5)
tar (5,7)(5,5) elm (6,0)(8,0)
max (7,4)(9,4) pup (5,3)(3,5)
mph (8,8)(6,8)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Wordseach
{
static class Program
{
readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}};
class Grid
{
public char[,] Cells = new char[nRows, nCols];
public List<string> Solutions = new List<string>();
public int NumAttempts;
}
readonly static int nRows = 10;
readonly static int nCols = 10;
readonly static int gridSize = nRows * nCols;
readonly static int minWords = 25;
readonly static Random rand = new Random();
static void Main(string[] args)
{
PrintResult(CreateWordSearch(ReadWords("unixdict.txt")));
}
private static List<string> ReadWords(string filename)
{
int maxLen = Math.Max(nRows, nCols);
return System.IO.File.ReadAllLines(filename)
.Select(s => s.Trim().ToLower())
.Where(s => Regex.IsMatch(s, "^[a-z]{3," + maxLen + "}$"))
.ToList();
}
private static Grid CreateWordSearch(List<string> words)
{
int numAttempts = 0;
while (++numAttempts < 100)
{
words.Shuffle();
var grid = new Grid();
int messageLen = PlaceMessage(grid, "Rosetta Code");
int target = gridSize - messageLen;
int cellsFilled = 0;
foreach (var word in words)
{
cellsFilled += TryPlaceWord(grid, word);
if (cellsFilled == target)
{
if (grid.Solutions.Count >= minWords)
{
grid.NumAttempts = numAttempts;
return grid;
}
else break; // grid is full but we didn't pack enough words, start over
}
}
}
return null;
}
private static int TryPlaceWord(Grid grid, string word)
{
int randDir = rand.Next(dirs.GetLength(0));
int randPos = rand.Next(gridSize);
for (int dir = 0; dir < dirs.GetLength(0); dir++)
{
dir = (dir + randDir) % dirs.GetLength(0);
for (int pos = 0; pos < gridSize; pos++)
{
pos = (pos + randPos) % gridSize;
int lettersPlaced = TryLocation(grid, word, dir, pos);
if (lettersPlaced > 0)
return lettersPlaced;
}
}
return 0;
}
private static int TryLocation(Grid grid, string word, int dir, int pos)
{
int r = pos / nCols;
int c = pos % nCols;
int len = word.Length;
// check bounds
if ((dirs[dir, 0] == 1 && (len + c) > nCols)
|| (dirs[dir, 0] == -1 && (len - 1) > c)
|| (dirs[dir, 1] == 1 && (len + r) > nRows)
|| (dirs[dir, 1] == -1 && (len - 1) > r))
return 0;
int rr, cc, i, overlaps = 0;
// check cells
for (i = 0, rr = r, cc = c; i < len; i++)
{
if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])
{
return 0;
}
cc += dirs[dir, 0];
rr += dirs[dir, 1];
}
// place
for (i = 0, rr = r, cc = c; i < len; i++)
{
if (grid.Cells[rr, cc] == word[i])
overlaps++;
else
grid.Cells[rr, cc] = word[i];
if (i < len - 1)
{
cc += dirs[dir, 0];
rr += dirs[dir, 1];
}
}
int lettersPlaced = len - overlaps;
if (lettersPlaced > 0)
{
grid.Solutions.Add($"{word,-10} ({c},{r})({cc},{rr})");
}
return lettersPlaced;
}
private static int PlaceMessage(Grid grid, string msg)
{
msg = Regex.Replace(msg.ToUpper(), "[^A-Z]", "");
int messageLen = msg.Length;
if (messageLen > 0 && messageLen < gridSize)
{
int gapSize = gridSize / messageLen;
for (int i = 0; i < messageLen; i++)
{
int pos = i * gapSize + rand.Next(gapSize);
grid.Cells[pos / nCols, pos % nCols] = msg[i];
}
return messageLen;
}
return 0;
}
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rand.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
private static void PrintResult(Grid grid)
{
if (grid == null || grid.NumAttempts == 0)
{
Console.WriteLine("No grid to display");
return;
}
int size = grid.Solutions.Count;
Console.WriteLine("Attempts: " + grid.NumAttempts);
Console.WriteLine("Number of words: " + size);
Console.WriteLine("\n 0 1 2 3 4 5 6 7 8 9");
for (int r = 0; r < nRows; r++)
{
Console.Write("\n{0} ", r);
for (int c = 0; c < nCols; c++)
Console.Write(" {0} ", grid.Cells[r, c]);
}
Console.WriteLine("\n");
for (int i = 0; i < size - 1; i += 2)
{
Console.WriteLine("{0} {1}", grid.Solutions[i],
grid.Solutions[i + 1]);
}
if (size % 2 == 1)
Console.WriteLine(grid.Solutions[size - 1]);
Console.ReadLine();
}
}
} |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #AppleScript | AppleScript | on wrapParagraph(para, lineWidth)
if (para is "") then return para
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to {space, tab} -- Doesn't include character id 160 (NO-BREAK SPACE).
script o
property wrds : para's text items -- Space- or tab-delimited chunks.
end script
set spaceWidth to (count space) -- ;-)
set spaceLeft to lineWidth
set theLines to {}
set i to 1
repeat with j from 1 to (count o's wrds)
set wordWidth to (count item j of o's wrds)
if (wordWidth + spaceWidth > spaceLeft) then
set end of theLines to text 1 thru (-1 - wordWidth) of (text from text item i to text item j of para)
set i to j
set spaceLeft to lineWidth - wordWidth
else
set spaceLeft to spaceLeft - (wordWidth + spaceWidth)
end if
end repeat
set end of theLines to text from text item i to end of para
set AppleScript's text item delimiters to character id 8232 -- U+2028 (LINE SEPARATOR).
set output to theLines as text
set AppleScript's text item delimiters to astid
return output
end wrapParagraph
local para
set para to "If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia."
return wrapParagraph(para, 70) & (linefeed & linefeed) & wrapParagraph(para, 40) |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func contains(a []string, s string) bool {
for _, e := range a {
if e == s {
return true
}
}
return false
}
func oneAway(a, b string) bool {
sum := 0
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
sum++
}
}
return sum == 1
}
func wordLadder(words []string, a, b string) {
l := len(a)
var poss []string
for _, word := range words {
if len(word) == l {
poss = append(poss, word)
}
}
todo := [][]string{{a}}
for len(todo) > 0 {
curr := todo[0]
todo = todo[1:]
var next []string
for _, word := range poss {
if oneAway(word, curr[len(curr)-1]) {
next = append(next, word)
}
}
if contains(next, b) {
curr = append(curr, b)
fmt.Println(strings.Join(curr, " -> "))
return
}
for i := len(poss) - 1; i >= 0; i-- {
if contains(next, poss[i]) {
copy(poss[i:], poss[i+1:])
poss[len(poss)-1] = ""
poss = poss[:len(poss)-1]
}
}
for _, s := range next {
temp := make([]string, len(curr))
copy(temp, curr)
temp = append(temp, s)
todo = append(todo, temp)
}
}
fmt.Println(a, "into", b, "cannot be done.")
}
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
words := make([]string, len(bwords))
for i, bword := range bwords {
words[i] = string(bword)
}
pairs := [][]string{
{"boy", "man"},
{"girl", "lady"},
{"john", "jane"},
{"child", "adult"},
}
for _, pair := range pairs {
wordLadder(words, pair[0], pair[1])
}
} |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the wheel or grid. Usually there will be a minimum word length of 3 or 4
characters. Each letter may only be used as many times as it appears in the wheel
or grid.
An example
N
D
E
O
K
G
E
L
W
Task
Write a program to solve the above "word wheel" puzzle.
Specifically:
Find all words of 3 or more letters using only the letters in the string ndeokgelw.
All words must contain the central letter K.
Each letter may be used only as many times as it appears in the string.
For this task we'll use lowercase English letters exclusively.
A "word" is defined to be any string contained in the file located at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt.
If you prefer to use a different dictionary, please state which one you have used.
Optional extra
Word wheel puzzles usually state that there is at least one nine-letter word to be found.
Using the above dictionary, find the 3x3 grids with at least one nine-letter
solution that generate the largest number of words of three or more letters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Delphi | Delphi |
program Word_wheel;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes;
function IsInvalid(s: string): Boolean;
var
c: char;
leters: set of char;
firstE: Boolean;
begin
Result := (s.Length < 3) or (s.IndexOf('k') = -1) or (s.Length > 9);
if not Result then
begin
leters := ['d', 'e', 'g', 'k', 'l', 'n', 'o', 'w'];
firstE := true;
for c in s do
begin
if c in leters then
if (c = 'e') and (firstE) then
firstE := false
else
Exclude(leters, AnsiChar(c))
else
exit(true);
end;
end;
end;
var
dict: TStringList;
i: Integer;
begin
dict := TStringList.Create;
dict.LoadFromFile('unixdict.txt');
for i := dict.count - 1 downto 0 do
if IsInvalid(dict[i]) then
dict.Delete(i);
Writeln('The following ', dict.Count, ' words are the solutions to the puzzle:');
Writeln(dict.Text);
dict.Free;
readln;
end.
|
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Liberty_BASIC | Liberty BASIC |
NoMainWin
WindowWidth = 270
WindowHeight = 290
UpperLeftX=int((DisplayWidth-WindowWidth)/2)
UpperLeftY=int((DisplayHeight-WindowHeight)/2)
Global variablesInitialized : variablesInitialized = 0
Global BackColor$ : BackColor$ = "0 0 0"
' BackColor$ = "255 255 255"
'now, right click randomizes BG
Global size : size = 1'4
global mousepoints.mouseX0, mousepoints.mouseY0, mousepoints.mouseX1, mousepoints.mouseY1
'StyleBits #main.gbox, 0, _WS_BORDER, 0, 0
GraphicBox #main.gbox, 0, 0, 253, 252
Open "Click Twice to Form Line" For Window As #main
Print #main, "TrapClose quit"
Print #main.gbox, "Down; Color Black"
Print #main.gbox, "Down; fill ";BackColor$
Print #main.gbox, "When leftButtonUp gBoxClick"
Print #main.gbox, "When rightButtonUp RandomBG"
Print #main.gbox, "Size "; size
result = drawAntiAliasedLine(126.5, 0, 126.5, 252, "255 0 0")
result = drawAntiAliasedLine(0, 126, 253, 126, "255 0 0")
result = drawAntiAliasedLine(0, 0, 253, 252, "255 0 0")
result = drawAntiAliasedLine(253, 0, 0, 252, "255 0 0")
Wait
Sub quit handle$
Close #main
End
End Sub
sub RandomBG handle$, MouseX, MouseY
BackColor$ = int(rnd(1)*256);" ";int(rnd(1)*256);" ";int(rnd(1)*256)
Print #main.gbox, "CLS; fill ";BackColor$
variablesInitialized = 0
end sub
Sub gBoxClick handle$, MouseX, MouseY
'We will use the mousepoints "struct" to hold the values
'that way they are retained between subroutine calls
If variablesInitialized = 0 Then
Print #main.gbox, "CLS; fill ";BackColor$
mousepoints.mouseX0 = MouseX
mousepoints.mouseY0 = MouseY
variablesInitialized = 1
Else
If variablesInitialized = 1 Then
mousepoints.mouseX1 = MouseX
mousepoints.mouseY1 = MouseY
variablesInitialized = 0
result = drawAntiAliasedLine(mousepoints.mouseX0, mousepoints.mouseY0, mousepoints.mouseX1, mousepoints.mouseY1, "255 0 0")
End If
End If
End Sub
Function Swap(Byref a,Byref b)
aTemp = b
b = a
a = aTemp
End Function
Function RoundtoInt(val)
RoundtoInt = Int(val + 0.5)
End Function
Function PlotAntiAliased(x, y, RGB$, b, steep)
RGB$ = Int(Val(Word$(BackColor$, 1))*(1-b) + Val(Word$(RGB$, 1)) * b) ; " " ; _
Int(Val(Word$(BackColor$, 2))*(1-b) + Val(Word$(RGB$, 3)) * b) ; " " ; _
Int(Val(Word$(BackColor$, 3))*(1-b) + Val(Word$(RGB$, 2)) * b)
if steep then 'x and y reversed
Print #main.gbox, "Down; Color " + RGB$ + "; Set " + str$(y) + " " + str$(x)
else
Print #main.gbox, "Down; Color " + RGB$ + "; Set " + str$(x) + " " + str$(y)
end if
End Function
Function fracPart(x)
fracPart = (x Mod 1)
End function
Function invFracPart(x)
invFracPart = (1 - fracPart(x))
End Function
Function drawAntiAliasedLine(x1, y1, x2, y2, RGB$)
If (x2 - x1)=0 Or (y2 - y1)=0 Then
Print #main.gbox, "Down; Color " + RGB$
result = BresenhamLine(x1, y1, x2, y2)
Exit Function
End If
steep = abs(x2 - x1) < abs(y2 - y1)
if steep then 'x and y should be reversed
result = Swap(x1, y1)
result = Swap(x2, y2)
end if
If (x2 < x1) Then
result = Swap(x1, x2)
result = Swap(y1, y2)
End If
dx = (x2 - x1)
dy = (y2 - y1)
grad = (dy/ dx)
'Handle the First EndPoint
xend = RoundtoInt(x1)
yend = y1 + grad * (xend - x1)
xgap = invFracPart(x1 + 0.5)
ix1 = xend
iy1 = Int(yend)
result = PlotAntiAliased(ix1, iy1, RGB$, invFracPart(yend) * xgap, steep )
result = PlotAntiAliased(ix1, (iy1 + size), RGB$, fracPart(yend) * xgap, steep )
yf = (yend + grad)
'Handle the Second EndPoint
xend = RoundtoInt(x2)
yend = y2 + grad * (xend - x2)
xgap = fracPart(x2 + 0.5)
ix2 = xend
iy2 = Int(yend)
result = PlotAntiAliased(ix2, iy2, RGB$, invFracPart(yend) * xgap, steep )
result = PlotAntiAliased(ix2, (iy2 + size), RGB$, fracPart(yend) * xgap, steep )
For x = ix1 + 1 To ix2 - 1
result = PlotAntiAliased(x, Int(yf), RGB$, invFracPart(yf), steep )
result = PlotAntiAliased(x, (Int(yf) + size), RGB$, fracPart(yf), steep )
yf = (yf + grad)
Next x
End Function
Function BresenhamLine(x0, y0, x1, y1)
dx = Abs(x1 - x0)
dy = Abs(y1 - y0)
sx = ((x1 > x0) + Not(x0 < x1))
sy = ((y1 > y0) + Not(y0 < y1))
errornum = (dx - dy)
Do While 1
Print #main.gbox, "Set " + str$(x0) + " " + str$(y0)
If (x0 = x1) And (y0 = y1) Then Exit Do
errornum2 = (2 * errornum)
If errornum2 > (-1 * dy) Then
errornum = (errornum - dy)
x0 = (x0 + sx)
End If
If errornum2 < dx Then
errornum = (errornum + dx)
y0 = (y0 + sy)
End If
Loop
End Function
|
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #Euphoria | Euphoria | function xmlquote(sequence s)
sequence r
r = ""
for i = 1 to length(s) do
if s[i] = '<' then
r &= "<"
elsif s[i] = '>' then
r &= ">"
elsif s[i] = '&' then
r &= "&"
elsif s[i] = '"' then
r &= """
elsif s[i] = '\'' then
r &= "'"
else
r &= s[i]
end if
end for
return r
end function
constant CharacterRemarks = {
{"April", "Bubbly: I'm > Tam and <= Emily"},
{"Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""},
{"Emily", "Short & shrift"}
}
puts(1,"<CharacterRemarks>\n")
for i = 1 to length(CharacterRemarks) do
printf(1," <CharacterName=\"%s\">",{xmlquote(CharacterRemarks[i][1])})
puts(1,xmlquote(CharacterRemarks[i][2]))
puts(1,"</Character>\n")
end for
puts(1,"</CharacterRemarks>\n") |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Delphi | Delphi |
//You need to use these units
uses
SysUtils,
Dialogs,
XMLIntf,
XMLDoc;
//..............................................
//This function process the XML
function GetStudents(aXMLInput: string): string;
var
XMLDoc: IXMLDocument;
i: Integer;
begin
//Creating the TXMLDocument instance
XMLDoc:= TXMLDocument.Create(nil);
//Loading8 the XML string
XMLDoc.LoadFromXML(aXMLInput);
//Parsing the xml document
for i:=0 to XMLDoc.DocumentElement.ChildNodes.Count - 1 do
Result:= Result + XMLDoc.DocumentElement.ChildNodes.Get(i).GetAttributeNS('Name', '') + #13#10;
//Removing the trailing #13#10 characters
Result:= Trim(Result);
end;
//..............................................
//Consuming code example (fragment)
var
XMLInput: string;
begin
XMLInput:= '<Students>' +
'<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />' +
'<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />' +
'<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />' +
'<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">' +
'<Pet Type="dog" Name="Rover" />' +
'</Student>' +
'<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />'+
'</Students>';
Showmessage(GetStudents(XMLInput));
end;
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Suneido | Suneido | array = Object('zero', 'one', 'two')
array.Add('three')
array.Add('five', at: 5)
array[4] = 'four'
Print(array[3]) --> 'three' |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams.
For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage.
Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.
A win is worth three points.
A draw/tie is worth one point.
A loss is worth zero points.
Task
Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them.
Calculate the standings points for each team with each combination of outcomes.
Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.
Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?".
Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.
| #Ruby | Ruby | teams = [:a, :b, :c, :d]
matches = teams.combination(2).to_a
outcomes = [:win, :draw, :loss]
gains = {win:[3,0], draw:[1,1], loss:[0,3]}
places_histogram = Array.new(4) {Array.new(10,0)}
# The Array#repeated_permutation method generates the 3^6 different
# possible outcomes
outcomes.repeated_permutation(6).each do |outcome|
results = Hash.new(0)
# combine this outcomes with the matches, and generate the points table
outcome.zip(matches).each do |decision, (team1, team2)|
results[team1] += gains[decision][0]
results[team2] += gains[decision][1]
end
# accumulate the results
results.values.sort.reverse.each_with_index do |points, place|
places_histogram[place][points] += 1
end
end
fmt = "%s :" + "%4s"*10
puts fmt % [" ", *0..9]
puts fmt % ["-", *["---"]*10]
places_histogram.each.with_index(1) {|hist,place| puts fmt % [place, *hist]} |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #PARI.2FGP | PARI/GP | f(x,pr)={
Strprintf(if(x>=10^pr,
Str("%.",pr-1,"e")
,
Str("%.",pr-#Str(x\1),"f")
),x)
};
wr(x,y,xprec,yprec)={
for(i=1,#x,
write("filename",f(x[i],xprec),"\t",f(y[i],yprec))
)
}; |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #MIPS_Assembly | MIPS Assembly | .data
doors: .space 100
num_str: .asciiz "Number "
comma_gap: .asciiz " is "
newline: .asciiz "\n"
.text
main:
# Clear all the cells to zero
li $t1, 100
la $t2, doors
clear_loop:
sb $0, ($t2)
add $t2, $t2, 1
sub $t1, $t1, 1
bnez $t1, clear_loop
# Now start the loops
li $t0, 1 # This will the the step size
li $t4, 1 # just an arbitrary 1
loop1:
move $t1, $t0 # Counter
la $t2, doors # Current pointer
add $t2, $t2, $t0
addi $t2, $t2, -1
loop2:
lb $t3, ($t2)
sub $t3, $t4, $t3
sb $t3, ($t2)
add $t1, $t1, $t0
add $t2, $t2, $t0
ble $t1, 100, loop2
addi $t0, $t0, 1
ble $t0, 100, loop1
# Now display everything
la $t0, doors
li $t1, 1
loop3:
li $v0, 4
la $a0, num_str
syscall
li $v0, 1
move $a0, $t1
syscall
li $v0, 4
la $a0, comma_gap
syscall
li $v0, 1
lb $a0, ($t0)
syscall
li $v0, 4,
la $a0, newline
syscall
addi $t0, $t0, 1
addi $t1, $t1, 1
bne $t1, 101 loop3
|
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Ruby | Ruby | require("rexml/document")
include REXML
(doc = Document.new) << XMLDecl.new
root = doc.add_element('root')
element = root.add_element('element')
element.add_text('Some text here')
# save to a string
# (the first argument to write() needs an object that understands "<<")
serialized = String.new
doc.write(serialized, 4)
puts serialized |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Scala | Scala | val xml = <root><element>Some text here</element></root>
scala.xml.XML.save(filename="output.xml", node=xml, enc="UTF-8", xmlDecl=true, doctype=null) |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. cobol-3d.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 cobol-area.
03 cobol-text-data PIC X(1030) VALUE "________/\\\\\\\\\____
- "____/\\\\\________/\\\\\\\\\\\\\__________/\\\\\________
- "/\\\_____________ _____/\\\////////_______/\\\//
- "/\\\_____\/\\\/////////\\\______/\\\///\\\_____\/\\\____
- "_________ ___/\\\/______________/\\\/__\///\\\__
- "_\/\\\_______\/\\\____/\\\/__\///\\\___\/\\\____________
- "_ __/\\\_______________/\\\______\//\\\__\/\\\\\
- "\\\\\\\\\____/\\\______\//\\\__\/\\\_____________
- " _\/\\\______________\/\\\_______\/\\\__\/\\\/////////\\\
- "__\/\\\_______\/\\\__\/\\\_____________ _\//\\\_
- "____________\//\\\______/\\\___\/\\\_______\/\\\__\//\\\
- "______/\\\___\/\\\_____________ __\///\\\_______
- "_____\///\\\__/\\\_____\/\\\_______\/\\\___\///\\\__/\\\
- "_____\/\\\_____________ ____\////\\\\\\\\\_____\
- "///\\\\\/______\/\\\\\\\\\\\\\/______\///\\\\\/______\/\
- "\\\\\\\\\\\\\\_ _______\/////////________\/////_
- "_______\/////////////__________\/////________\//////////
- "/////__" *> " Sorry for the syntax highlighting.
.
03 cobol-text-table REDEFINES cobol-text-data.
05 cobol-text PIC X(103) OCCURS 10 TIMES.
01 i PIC 99.
01 j PIC 9(4).
PROCEDURE DIVISION.
*> Display 'COBOL' line-by-line applying a shadow effect.
PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i
MOVE 1 TO j
PERFORM UNTIL 103 < j
*> When the top of a letter meets the right edge,
*> take care to shadow only the wall ('/').
IF cobol-text (i) (j:4) = "\\\/"
DISPLAY cobol-text (i) (j:3) AT LINE i COL j
WITH FOREGROUND-COLOR 7, HIGHLIGHT
ADD 3 TO j
DISPLAY cobol-text (i) (j:1) AT LINE i COL j
WITH FOREGROUND-COLOR 0, HIGHLIGHT
ADD 1 TO j
EXIT PERFORM CYCLE
END-IF
*> Apply shadows to the walls, base and the char
*> before the base.
IF cobol-text (i) (j:1) = "/"
OR cobol-text (i) (FUNCTION SUM(j, 1):1) = "/"
OR cobol-text (i) (FUNCTION SUM(j, 1):2)
= "\/"
DISPLAY cobol-text (i) (j:1) AT LINE i COL j
WITH FOREGROUND-COLOR 0, HIGHLIGHT
*> Do not apply a shadow to anything else.
ELSE
DISPLAY cobol-text (i) (j:1) AT LINE i COL j
WITH FOREGROUND-COLOR 7 , HIGHLIGHT
END-IF
ADD 1 TO j
END-PERFORM
END-PERFORM
*> Prompt the user so that they have a chance to see the
*> ASCII art, as sometimes the screen data is overwritten by
*> what was on the console before starting the program.
DISPLAY "Press enter to stop appreciating COBOL in 3D."
AT LINE 11 COL 1
ACCEPT i AT LINE 11 COL 46
GOBACK
. |
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may overlap but are not allowed to zigzag, or wrap around.
Task
Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.
The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message.
Pack a minimum of 25 words into the grid.
Print the resulting grid and the solutions.
Example
0 1 2 3 4 5 6 7 8 9
0 n a y r y R e l m f
1 y O r e t s g n a g
2 t n e d i S k y h E
3 n o t n c p c w t T
4 a l s u u n T m a x
5 r o k p a r i s h h
6 a A c f p a e a c C
7 u b u t t t O l u n
8 g y h w a D h p m u
9 m i r p E h o g a n
parish (3,5)(8,5) gangster (9,1)(2,1)
paucity (4,6)(4,0) guaranty (0,8)(0,1)
prim (3,9)(0,9) huckster (2,8)(2,1)
plasm (7,8)(7,4) fancy (3,6)(7,2)
hogan (5,9)(9,9) nolo (1,2)(1,5)
under (3,4)(3,0) chatham (8,6)(8,0)
ate (4,8)(6,6) nun (9,7)(9,9)
butt (1,7)(4,7) hawk (9,5)(6,2)
why (3,8)(1,8) ryan (3,0)(0,0)
fay (9,0)(7,2) much (8,8)(8,5)
tar (5,7)(5,5) elm (6,0)(8,0)
max (7,4)(9,4) pup (5,3)(3,5)
mph (8,8)(6,8)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.2B.2B | C++ |
#include <iomanip>
#include <ctime>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;
class Cell {
public:
Cell() : val( 0 ), cntOverlap( 0 ) {}
char val; int cntOverlap;
};
class Word {
public:
Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) :
word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}
bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }
std::string word;
int cols, rows, cole, rowe, dx, dy;
};
class words {
public:
void create( std::string& file ) {
std::ifstream f( file.c_str(), std::ios_base::in );
std::string word;
while( f >> word ) {
if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;
if( word.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" ) != word.npos ) continue;
dictionary.push_back( word );
}
f.close();
std::random_shuffle( dictionary.begin(), dictionary.end() );
buildPuzzle();
}
void printOut() {
std::cout << "\t";
for( int x = 0; x < WID; x++ ) std::cout << x << " ";
std::cout << "\n\n";
for( int y = 0; y < HEI; y++ ) {
std::cout << y << "\t";
for( int x = 0; x < WID; x++ )
std::cout << puzzle[x][y].val << " ";
std::cout << "\n";
}
size_t wid1 = 0, wid2 = 0;
for( size_t x = 0; x < used.size(); x++ ) {
if( x & 1 ) {
if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();
} else {
if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();
}
}
std::cout << "\n";
std::vector<Word>::iterator w = used.begin();
while( w != used.end() ) {
std::cout << std::right << std::setw( wid1 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") ("
<< ( *w ).cole << ", " << ( *w ).rowe << ")\t";
w++;
if( w == used.end() ) break;
std::cout << std::setw( wid2 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") ("
<< ( *w ).cole << ", " << ( *w ).rowe << ")\n";
w++;
}
std::cout << "\n\n";
}
private:
void addMsg() {
std::string msg = "ROSETTACODE";
int stp = 9, p = rand() % stp;
for( size_t x = 0; x < msg.length(); x++ ) {
puzzle[p % WID][p / HEI].val = msg.at( x );
p += rand() % stp + 4;
}
}
int getEmptySpaces() {
int es = 0;
for( int y = 0; y < HEI; y++ ) {
for( int x = 0; x < WID; x++ ) {
if( !puzzle[x][y].val ) es++;
}
}
return es;
}
bool check( std::string word, int c, int r, int dc, int dr ) {
for( size_t a = 0; a < word.length(); a++ ) {
if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;
if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;
c += dc; r += dr;
}
return true;
}
bool setWord( std::string word, int c, int r, int dc, int dr ) {
if( !check( word, c, r, dc, dr ) ) return false;
int sx = c, sy = r;
for( size_t a = 0; a < word.length(); a++ ) {
if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );
else puzzle[c][r].cntOverlap++;
c += dc; r += dr;
}
used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );
return true;
}
bool add2Puzzle( std::string word ) {
int x = rand() % WID, y = rand() % HEI,
z = rand() % 8;
for( int d = z; d < z + 8; d++ ) {
switch( d % 8 ) {
case 0: if( setWord( word, x, y, 1, 0 ) ) return true; break;
case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;
case 2: if( setWord( word, x, y, 0, 1 ) ) return true; break;
case 3: if( setWord( word, x, y, 1, -1 ) ) return true; break;
case 4: if( setWord( word, x, y, -1, 0 ) ) return true; break;
case 5: if( setWord( word, x, y, -1, 1 ) ) return true; break;
case 6: if( setWord( word, x, y, 0, -1 ) ) return true; break;
case 7: if( setWord( word, x, y, 1, 1 ) ) return true; break;
}
}
return false;
}
void clearWord() {
if( used.size() ) {
Word lastW = used.back();
used.pop_back();
for( size_t a = 0; a < lastW.word.length(); a++ ) {
if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {
puzzle[lastW.cols][lastW.rows].val = 0;
}
if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {
puzzle[lastW.cols][lastW.rows].cntOverlap--;
}
lastW.cols += lastW.dx; lastW.rows += lastW.dy;
}
}
}
void buildPuzzle() {
addMsg();
int es = 0, cnt = 0;
size_t idx = 0;
do {
for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {
if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;
if( add2Puzzle( *w ) ) {
es = getEmptySpaces();
if( !es && used.size() >= MIN_WORD_CNT )
return;
}
}
clearWord();
std::random_shuffle( dictionary.begin(), dictionary.end() );
} while( ++cnt < 100 );
}
std::vector<Word> used;
std::vector<std::string> dictionary;
Cell puzzle[WID][HEI];
};
int main( int argc, char* argv[] ) {
unsigned s = unsigned( time( 0 ) );
srand( s );
words w; w.create( std::string( "unixdict.txt" ) );
w.printOut();
return 0;
}
|
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #Arturo | Arturo | txt: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur."
print wordwrap txt
print ""
print wordwrap.at:45 txt |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell | import System.IO (readFile)
import Control.Monad (foldM)
import Data.List (intercalate)
import qualified Data.Set as S
distance :: String -> String -> Int
distance s1 s2 = length $ filter not $ zipWith (==) s1 s2
wordLadders :: [String] -> String -> String -> [[String]]
wordLadders dict start end
| length start /= length end = []
| otherwise = [wordSpace] >>= expandFrom start >>= shrinkFrom end
where
wordSpace = S.fromList $ filter ((length start ==) . length) dict
expandFrom s = go [[s]]
where
go (h:t) d
| S.null d || S.null f = []
| end `S.member` f = [h:t]
| otherwise = go (S.elems f:h:t) (d S.\\ f)
where
f = foldr (\w -> S.union (S.filter (oneStepAway w) d)) mempty h
shrinkFrom = scanM (filter . oneStepAway)
oneStepAway x = (1 ==) . distance x
scanM f x = fmap snd . foldM g (x,[x])
where g (b, r) a = (\x -> (x, x:r)) <$> f b a
wordLadder :: [String] -> String -> String -> [String]
wordLadder d s e = case wordLadders d s e of
[] -> []
h:_ -> h
showChain [] = putStrLn "No chain"
showChain ch = putStrLn $ intercalate " -> " ch
main = do
dict <- lines <$> readFile "unixdict.txt"
showChain $ wordLadder dict "boy" "man"
showChain $ wordLadder dict "girl" "lady"
showChain $ wordLadder dict "john" "jane"
showChain $ wordLadder dict "alien" "drool"
showChain $ wordLadder dict "child" "adult" |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the wheel or grid. Usually there will be a minimum word length of 3 or 4
characters. Each letter may only be used as many times as it appears in the wheel
or grid.
An example
N
D
E
O
K
G
E
L
W
Task
Write a program to solve the above "word wheel" puzzle.
Specifically:
Find all words of 3 or more letters using only the letters in the string ndeokgelw.
All words must contain the central letter K.
Each letter may be used only as many times as it appears in the string.
For this task we'll use lowercase English letters exclusively.
A "word" is defined to be any string contained in the file located at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt.
If you prefer to use a different dictionary, please state which one you have used.
Optional extra
Word wheel puzzles usually state that there is at least one nine-letter word to be found.
Using the above dictionary, find the 3x3 grids with at least one nine-letter
solution that generate the largest number of words of three or more letters.
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
| #F.23 | F# |
// Word Wheel: Nigel Galloway. May 25th., 2021
let fG k n g=g|>Seq.exists(fun(n,_)->n=k) && g|>Seq.forall(fun(k,g)->Map.containsKey k n && g<=n.[k])
let wW n g=let fG=fG(Seq.item 4 g)(g|>Seq.countBy id|>Map.ofSeq) in seq{use n=System.IO.File.OpenText(n) in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter(fun n->2<(Seq.length n)&&(Seq.countBy id>>fG)n)
wW "unixdict.txt" "ndeokgelw"|>Seq.iter(printfn "%s")
|
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the wheel or grid. Usually there will be a minimum word length of 3 or 4
characters. Each letter may only be used as many times as it appears in the wheel
or grid.
An example
N
D
E
O
K
G
E
L
W
Task
Write a program to solve the above "word wheel" puzzle.
Specifically:
Find all words of 3 or more letters using only the letters in the string ndeokgelw.
All words must contain the central letter K.
Each letter may be used only as many times as it appears in the string.
For this task we'll use lowercase English letters exclusively.
A "word" is defined to be any string contained in the file located at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt.
If you prefer to use a different dictionary, please state which one you have used.
Optional extra
Word wheel puzzles usually state that there is at least one nine-letter word to be found.
Using the above dictionary, find the 3x3 grids with at least one nine-letter
solution that generate the largest number of words of three or more letters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: assocs io.encodings.ascii io.files kernel math
math.statistics prettyprint sequences sorting ;
! Only consider words longer than two letters and words that
! contain elt.
: pare ( elt seq -- new-seq )
[ [ member? ] keep length 2 > and ] with filter ;
: words ( input-str path -- seq )
[ [ midpoint@ ] keep nth ] [ ascii file-lines pare ] bi* ;
: ?<= ( m n/f -- ? ) dup f = [ nip ] [ <= ] if ;
! Can we make sequence 1 with the elements in sequence 2?
: can-make? ( seq1 seq2 -- ? )
[ histogram ] bi@ [ swapd at ?<= ] curry assoc-all? ;
: solve ( input-str path -- seq )
[ words ] keepd [ can-make? ] curry filter ;
"ndeokgelw" "unixdict.txt" solve [ length ] sort-with . |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[ReverseFractionalPart, ReplacePixelWithAlpha, DrawEndPoint, DrawLine]
ReverseFractionalPart[x_] := 1 - FractionalPart[x]
ReplacePixelWithAlpha[img_Image, pos_ -> colvals : {_, _, _},
alpha_] := Module[{vals,},
vals = PixelValue[img, pos];
vals = (1 - alpha) vals + alpha colvals;
ReplacePixelValue[img, pos -> vals]
]
DrawEndPoint[img_Image, pt : {x_, y_}, grad_, p_] :=
Module[{xend, yend, xgap, px, py, i},
xend = Round[x];
yend = y + grad (xend - x);
xgap = ReverseFractionalPart[x + 0.5];
{px, py} = Floor[{xend, yend}];
i = ReplacePixelWithAlpha[img, p[{x, py}] -> {1, 1, 1}, ReverseFractionalPart[yend] xgap];
i = ReplacePixelWithAlpha[i, p[{x, py + 1}] -> {1, 1, 1}, FractionalPart[yend] xgap];
{px, i}
]
DrawLine[img_Image, p1 : {_, _}, p2 : {_, _}] :=
Module[{x1, x2, y1, y2, steep, p, grad, intery, xend, yend, x, y,
xstart, ystart, dx, dy, i},
{x1, y1} = p1;
{x2, y2} = p2;
dx = x2 - x1;
dy = y2 - y1;
steep = Abs[dx] < Abs[dy];
p = If[steep, Reverse[#], #] &;
If[steep,
{x1, y1, x2, y2, dx, dy} = {y1, x1, y2, x2, dy, dx}
];
If[x2 < x1,
{x1, x2, y1, y2} = {x2, x1, y2, y1}
];
grad = dy/dx;
intery = y1 + ReverseFractionalPart[x1] grad;
{xstart, i} = DrawEndPoint[img, p[p1], grad, p];
xstart += 1;
{xend, i} = DrawEndPoint[i, p[p2], grad, p];
Do[
y = Floor[intery];
i = ReplacePixelWithAlpha[i, p[{x, y}] -> {1, 1, 1}, ReverseFractionalPart[intery]];
i = ReplacePixelWithAlpha[i, p[{x, y + 1}] -> {1, 1, 1}, FractionalPart[intery]];
intery += grad
,
{x, xstart, xend}
];
i
]
image = ConstantImage[Black, {100, 100}];
Fold[DrawLine[#1, {20, 10}, #2] &, image, AngleVector[{20, 10}, {75, #}] & /@ Subdivide[0, Pi/2, 10]] |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Nim | Nim | import math
import imageman
template ipart(x: float): float = floor(x)
template fpart(x: float): float = x - ipart(x)
template rfpart(x: float): float = 1 - fpart(x)
const
BG = ColorRGBF64([0.0, 0.0, 0.0])
FG = ColorRGBF64([1.0, 1.0, 1.0])
func plot(img: var Image; x, y: int; c: float) =
## Draw a point with brigthness c.
let d = 1 - c
img[x, y] = ColorRGBF64([BG.r * d + FG.r * c, BG.g * d + FG.g * c, BG.b * d + FG.b * c])
func drawLine(img: var Image; x0, y0, x1, y1: float) =
## Draw an anti-aliased line from (x0, y0) to (x1, y1).
var (x0, y0, x1, y1) = (x0, y0, x1, y1)
let steep = abs(y1 - y0) > abs(x1 - x0)
if steep:
swap x0, y0
swap x1, y1
if x0 > x1:
swap x0, x1
swap y0, y1
let dx = x1 - x0
let dy = y1 - y0
var gradient = dy / dx
if dx == 0:
gradient = 1
# Handle first endpoint.
var xend = round(x0)
var yend = y0 + gradient * (xend - x0)
var xgap = rfpart(x0 + 0.5)
let xpxl1 = xend.toInt
let ypxl1 = yend.toInt
if steep:
img.plot(ypxl1, xpxl1, rfpart(yend) * xgap)
img.plot(ypxl1 + 1, xpxl1, fpart(yend) * xgap)
else:
img.plot(xpxl1, ypxl1, rfpart(yend) * xgap)
img.plot(xpxl1, ypxl1 + 1, fpart(yend) * xgap)
var intery = yend + gradient # First y-intersection for the main loop.
# Handle second endpoint.
xend = round(x1)
yend = y1 + gradient * (xend - x1)
xgap = fpart(x1 + 0.5)
let xpxl2 = xend.toInt
let ypxl2 = yend.toInt
if steep:
img.plot(ypxl2, xpxl2, rfpart(yend) * xgap)
img.plot(ypxl2 + 1, xpxl2, fpart(yend) * xgap)
else:
img.plot(xpxl2, ypxl2, rfpart(yend) * xgap)
img.plot(xpxl2, ypxl2 + 1, fpart(yend) * xgap)
# Main loop.
if steep:
for x in (xpxl1 + 1)..(xpxl2 - 1):
img.plot(intery.int, x, rfpart(intery))
img.plot(intery.int + 1, x, fpart(intery))
intery += gradient
else:
for x in (xpxl1 + 1)..(xpxl2 - 1):
img.plot(x, intery.int, rfpart(intery))
img.plot(x, intery.int + 1, fpart(intery))
intery += gradient
when isMainModule:
var img = initImage[ColorRGBF64](800, 800)
img.fill(BG)
for x1 in countup(100, 700, 60):
img.drawLine(400, 700, x1.toFloat, 100)
img.savePNG("xiaoling_wu.png", compression = 9) |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #F.23 | F# | #light
open System.Xml
type Character = {name : string; comment : string }
let data = [
{ name = "April"; comment = "Bubbly: I'm > Tam and <= Emily"}
{ name = "Tam O'Shanter"; comment = "Burns: \"When chapman billies leave the street ...\""}
{ name = "Emily"; comment = "Short & shrift"} ]
let doxml (characters : Character list) =
let doc = new XmlDocument()
let root = doc.CreateElement("CharacterRemarks")
doc.AppendChild root |> ignore
Seq.iter (fun who ->
let node = doc.CreateElement("Character")
node.SetAttribute("name", who.name)
doc.CreateTextNode(who.comment)
|> node.AppendChild |> ignore
root.AppendChild node |> ignore
) characters
doc.OuterXml |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Erlang | Erlang |
-module( xml_input ).
-export( [task/0] ).
-include_lib("xmerl/include/xmerl.hrl").
task() ->
{XML, []} = xmerl_scan:string( xml(), [{encoding, "iso-10646-utf-1"}] ),
Attributes = lists:flatten( [X || #xmlElement{name='Student', attributes=X} <- XML#xmlElement.content] ),
[io:fwrite("~s~n", [X]) || #xmlAttribute{name='Name', value=X} <- Attributes].
xml() -> "<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />
<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />
<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">
<Pet Type=\"dog\" Name=\"Rover\" />
</Student>
<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />
</Students>".
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Swift | Swift | // Arrays are typed in Swift, however, using the Any object we can add any type. Swift does not support fixed length arrays
var anyArray = [Any]()
anyArray.append("foo") // Adding to an Array
anyArray.append(1) // ["foo", 1]
anyArray.removeAtIndex(1) // Remove object
anyArray[0] = "bar" // ["bar"] |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams.
For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage.
Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.
A win is worth three points.
A draw/tie is worth one point.
A loss is worth zero points.
Task
Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them.
Calculate the standings points for each team with each combination of outcomes.
Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.
Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?".
Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.
| #Scala | Scala | object GroupStage extends App { //team left digit vs team right digit
val games = Array("12", "13", "14", "23", "24", "34")
val points = Array.ofDim[Int](4, 10) //playing 3 games, points range from 0 to 9
var results = "000000" //start with left teams all losing
private def nextResult: Boolean = {
if (results == "222222") false
else {
results = Integer.toString(Integer.parseInt(results, 3) + 1, 3)
while (results.length < 6) results = "0" + results //left pad with 0s
true
}
}
do {
val records = Array(0, 0, 0, 0)
for (i <- results.indices.reverse by -1) {
results(i) match {
case '2' => records(games(i)(0) - '1') += 3
case '1' => //draw
records(games(i)(0) - '1') += 1
records(games(i)(1) - '1') += 1
case '0' => records(games(i)(1) - '1') += 3
}
}
java.util.Arrays.sort(records) //sort ascending, first place team on the right
points(0)(records(0)) += 1
points(1)(records(1)) += 1
points(2)(records(2)) += 1
points(3)(records(3)) += 1
} while (nextResult)
println("First place: " + points(3).mkString("[",", ","]"))
println("Second place: " + points(2).mkString("[",", ","]"))
println("Third place: " + points(1).mkString("[",", ","]"))
println("Fourth place: " + points(0).mkString("[",", ","]"))
} |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Pascal | Pascal | Program WriteNumbers;
const
x: array [1..4] of double = (1, 2, 3, 1e11);
xprecision = 3;
yprecision = 5;
baseDigits = 7;
var
i: integer;
filename: text;
begin
assign (filename, 'filename');
rewrite (filename);
for i := 1 to 4 do
writeln (filename, x[i]:baseDigits+xprecision, sqrt(x[i]):baseDigits+yprecision);
close (filename);
end. |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Perl | Perl | use autodie;
sub writedat {
my ($filename, $x, $y, $xprecision, $yprecision) = @_;
open my $fh, ">", $filename;
for my $i (0 .. $#$x) {
printf $fh "%.*g\t%.*g\n", $xprecision||3, $x->[$i], $yprecision||5, $y->[$i];
}
close $fh;
}
my @x = (1, 2, 3, 1e11);
my @y = map sqrt, @x;
writedat("sqrt.dat", \@x, \@y); |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Mirah | Mirah | import java.util.ArrayList
class Door
:state
def initialize
@state=false
end
def closed?; !@state; end
def open?; @state; end
def close; @state=false; end
def open; @state=true; end
def toggle
if closed?
open
else
close
end
end
def toString; Boolean.toString(@state); end
end
doors=ArrayList.new
1.upto(100) do
doors.add(Door.new)
end
1.upto(100) do |multiplier|
index = 0
doors.each do |door|
Door(door).toggle if (index+1)%multiplier == 0
index += 1
end
end
i = 0
doors.each do |door|
puts "Door #{i+1} is #{door}."
i+=1
end
|
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Sidef | Sidef | require('XML::Simple');
print %S'XML::Simple'.XMLout(
:(root => :( element => 'Some text here' )),
NoAttr => 1, RootName => '',
); |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Tcl | Tcl | package require tdom
set d [dom createDocument root]
set root [$d documentElement]
$root appendChild [$d createElement element]
[$root firstChild] appendChild [$d createTextNode "Some text here"]
$d asXML |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #Common_Lisp | Common Lisp |
(ql:quickload :cl-ppcre)
(defvar txt
"
xxxx xxxx x x x x xxxx x x x x xxxx xxxxx
x x x x xx xx xx xx x x xx x x x x x x
x x x x xx x x xx x x x x x x x x xxx x x
x x x x x x x x x x x x x x xxx xxxxx
x x x x x x x x x x x xx x x x x x
xxxx xxxx x x x x xxxx x x xxxxx x xxxx x
"
)
(princ (cl-ppcre:regex-replace-all " " (cl-ppcre:regex-replace-all "x" txt "_/") " " ))
|
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may overlap but are not allowed to zigzag, or wrap around.
Task
Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.
The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message.
Pack a minimum of 25 words into the grid.
Print the resulting grid and the solutions.
Example
0 1 2 3 4 5 6 7 8 9
0 n a y r y R e l m f
1 y O r e t s g n a g
2 t n e d i S k y h E
3 n o t n c p c w t T
4 a l s u u n T m a x
5 r o k p a r i s h h
6 a A c f p a e a c C
7 u b u t t t O l u n
8 g y h w a D h p m u
9 m i r p E h o g a n
parish (3,5)(8,5) gangster (9,1)(2,1)
paucity (4,6)(4,0) guaranty (0,8)(0,1)
prim (3,9)(0,9) huckster (2,8)(2,1)
plasm (7,8)(7,4) fancy (3,6)(7,2)
hogan (5,9)(9,9) nolo (1,2)(1,5)
under (3,4)(3,0) chatham (8,6)(8,0)
ate (4,8)(6,6) nun (9,7)(9,9)
butt (1,7)(4,7) hawk (9,5)(6,2)
why (3,8)(1,8) ryan (3,0)(0,0)
fay (9,0)(7,2) much (8,8)(8,5)
tar (5,7)(5,5) elm (6,0)(8,0)
max (7,4)(9,4) pup (5,3)(3,5)
mph (8,8)(6,8)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #D | D | import std.random : Random, uniform, randomShuffle;
import std.stdio;
immutable int[][] dirs = [
[1, 0], [ 0, 1], [ 1, 1],
[1, -1], [-1, 0],
[0, -1], [-1, -1], [-1, 1]
];
enum nRows = 10;
enum nCols = 10;
enum gridSize = nRows * nCols;
enum minWords = 25;
auto rnd = Random();
class Grid {
int numAttempts;
char[nRows][nCols] cells;
string[] solutions;
this() {
for(int row=0; row<nRows; ++row) {
cells[row] = 0;
}
}
}
void main() {
printResult(createWordSearch(readWords("unixdict.txt")));
}
string[] readWords(string filename) {
import std.algorithm : all, max;
import std.ascii : isAlpha;
import std.string : chomp, toLower;
auto maxlen = max(nRows, nCols);
string[] words;
auto source = File(filename);
foreach(line; source.byLine) {
chomp(line);
if (line.length >= 3 && line.length <= maxlen) {
if (all!isAlpha(line)) {
words ~= line.toLower.idup;
}
}
}
return words;
}
Grid createWordSearch(string[] words) {
Grid grid;
int numAttempts;
outer:
while(++numAttempts < 100) {
randomShuffle(words);
grid = new Grid();
int messageLen = placeMessage(grid, "Rosetta Code");
int target = gridSize - messageLen;
int cellsFilled;
foreach (string word; words) {
cellsFilled += tryPlaceWord(grid, word);
if (cellsFilled == target) {
if (grid.solutions.length >= minWords) {
grid.numAttempts = numAttempts;
break outer;
} else break; // grid is full but we didn't pack enough words, start over
}
}
}
return grid;
}
int placeMessage(Grid grid, string msg) {
import std.algorithm : filter;
import std.ascii : isUpper;
import std.conv : to;
import std.string : toUpper;
msg = to!string(msg.toUpper.filter!isUpper);
if (msg.length > 0 && msg.length < gridSize) {
int gapSize = gridSize / msg.length;
for (int i=0; i<msg.length; i++) {
int pos = i * gapSize + uniform(0, gapSize, rnd);
grid.cells[pos / nCols][pos % nCols] = msg[i];
}
return msg.length;
}
return 0;
}
int tryPlaceWord(Grid grid, string word) {
int randDir = uniform(0, dirs.length, rnd);
int randPos = uniform(0, gridSize, rnd);
for (int dir=0; dir<dirs.length; dir++) {
dir = (dir + randDir) % dirs.length;
for (int pos=0; pos<gridSize; pos++) {
pos = (pos + randPos) % gridSize;
int lettersPlaced = tryLocation(grid, word, dir, pos);
if (lettersPlaced > 0) {
return lettersPlaced;
}
}
}
return 0;
}
int tryLocation(Grid grid, string word, int dir, int pos) {
import std.format;
int r = pos / nCols;
int c = pos % nCols;
int len = word.length;
// check bounds
if ((dirs[dir][0] == 1 && (len + c) > nCols)
|| (dirs[dir][0] == -1 && (len - 1) > c)
|| (dirs[dir][1] == 1 && (len + r) > nRows)
|| (dirs[dir][1] == -1 && (len - 1) > r)) {
return 0;
}
int i, rr, cc, overlaps = 0;
// check cells
for (i=0, rr=r, cc=c; i<len; i++) {
if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word[i]) {
return 0;
}
cc += dirs[dir][0];
rr += dirs[dir][1];
}
// place
for (i=0, rr=r, cc=c; i<len; i++) {
if (grid.cells[rr][cc] == word[i]) {
overlaps++;
} else {
grid.cells[rr][cc] = word[i];
}
if (i < len - 1) {
cc += dirs[dir][0];
rr += dirs[dir][1];
}
}
int lettersPlaced = len - overlaps;
if (lettersPlaced > 0) {
grid.solutions ~= format("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr);
}
return lettersPlaced;
}
void printResult(Grid grid) {
if (grid is null || grid.numAttempts == 0) {
writeln("No grid to display");
return;
}
int size = grid.solutions.length;
writeln("Attempts: ", grid.numAttempts);
writeln("Number of words: ", size);
writeln("\n 0 1 2 3 4 5 6 7 8 9");
for (int r=0; r<nRows; r++) {
writef("\n%d ", r);
for (int c=0; c<nCols; c++) {
writef(" %c ", grid.cells[r][c]);
}
}
writeln;
writeln;
for (int i=0; i<size-1; i+=2) {
writef("%s %s\n", grid.solutions[i], grid.solutions[i + 1]);
}
if (size % 2 == 1) {
writeln(grid.solutions[size - 1]);
}
} |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #AutoHotkey | AutoHotkey | MsgBox, % "72`n" WrapText(Clipboard, 72) "`n`n80`n" WrapText(Clipboard, 80)
return
WrapText(Text, LineLength) {
StringReplace, Text, Text, `r`n, %A_Space%, All
while (p := RegExMatch(Text, "(.{1," LineLength "})(\s|\R+|$)", Match, p ? p + StrLen(Match) : 1))
Result .= Match1 ((Match2 = A_Space || Match2 = A_Tab) ? "`n" : Match2)
return, Result
} |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.IntStream;
public class WordLadder {
private static int distance(String s1, String s2) {
assert s1.length() == s2.length();
return (int) IntStream.range(0, s1.length())
.filter(i -> s1.charAt(i) != s2.charAt(i))
.count();
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {
wordLadder(words, fw, tw, 8);
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {
if (fw.length() != tw.length()) {
throw new IllegalArgumentException("From word and to word must have the same length");
}
Set<String> ws = words.get(fw.length());
if (ws.contains(fw)) {
List<String> primeList = new ArrayList<>();
primeList.add(fw);
PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {
int cmp1 = Integer.compare(chain1.size(), chain2.size());
if (cmp1 == 0) {
String last1 = chain1.get(chain1.size() - 1);
int d1 = distance(last1, tw);
String last2 = chain2.get(chain2.size() - 1);
int d2 = distance(last2, tw);
return Integer.compare(d1, d2);
}
return cmp1;
});
queue.add(primeList);
while (queue.size() > 0) {
List<String> curr = queue.remove();
if (curr.size() > limit) {
continue;
}
String last = curr.get(curr.size() - 1);
for (String word : ws) {
if (distance(last, word) == 1) {
if (word.equals(tw)) {
curr.add(word);
System.out.println(String.join(" -> ", curr));
return;
}
if (!curr.contains(word)) {
List<String> cp = new ArrayList<>(curr);
cp.add(word);
queue.add(cp);
}
}
}
}
}
System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw);
}
public static void main(String[] args) throws IOException {
Map<Integer, Set<String>> words = new HashMap<>();
for (String line : Files.readAllLines(Path.of("unixdict.txt"))) {
Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);
wl.add(line);
}
wordLadder(words, "boy", "man");
wordLadder(words, "girl", "lady");
wordLadder(words, "john", "jane");
wordLadder(words, "child", "adult");
wordLadder(words, "cat", "dog");
wordLadder(words, "lead", "gold");
wordLadder(words, "white", "black");
wordLadder(words, "bubble", "tickle", 12);
}
} |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the wheel or grid. Usually there will be a minimum word length of 3 or 4
characters. Each letter may only be used as many times as it appears in the wheel
or grid.
An example
N
D
E
O
K
G
E
L
W
Task
Write a program to solve the above "word wheel" puzzle.
Specifically:
Find all words of 3 or more letters using only the letters in the string ndeokgelw.
All words must contain the central letter K.
Each letter may be used only as many times as it appears in the string.
For this task we'll use lowercase English letters exclusively.
A "word" is defined to be any string contained in the file located at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt.
If you prefer to use a different dictionary, please state which one you have used.
Optional extra
Word wheel puzzles usually state that there is at least one nine-letter word to be found.
Using the above dictionary, find the 3x3 grids with at least one nine-letter
solution that generate the largest number of words of three or more letters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC |
#include "file.bi"
Function String_Split(s_in As String,chars As String,result() As String) As Long
Dim As Long ctr,ctr2,k,n,LC=Len(chars)
Dim As boolean tally(Len(s_in))
#macro check_instring()
n=0
While n<Lc
If chars[n]=s_in[k] Then
tally(k)=true
If (ctr2-1) Then ctr+=1
ctr2=0
Exit While
End If
n+=1
Wend
#endmacro
#macro split()
If tally(k) Then
If (ctr2-1) Then ctr+=1:result(ctr)=Mid(s_in,k+2-ctr2,ctr2-1)
ctr2=0
End If
#endmacro
'================== LOOP TWICE =======================
For k =0 To Len(s_in)-1
ctr2+=1:check_instring()
Next k
if ctr=0 then
if len(s_in) andalso instr(chars,chr(s_in[0])) then ctr=1':beep
end if
If ctr Then Redim result(1 To ctr): ctr=0:ctr2=0 Else Return 0
For k =0 To Len(s_in)-1
ctr2+=1:split()
Next k
'===================== Last one ========================
If ctr2>0 Then
Redim Preserve result(1 To ctr+1)
result(ctr+1)=Mid(s_in,k+1-ctr2,ctr2)
End If
Return Ubound(result)
End Function
Function loadfile(file As String) As String
If Fileexists(file)=0 Then Print file;" not found":Sleep:End
Dim As Long f=Freefile
Open file For Binary Access Read As #f
Dim As String text
If Lof(f) > 0 Then
text = String(Lof(f), 0)
Get #f, , text
End If
Close #f
Return text
End Function
Function tally(SomeString As String,PartString As String) As Long
Dim As Long LenP=Len(PartString),count
Dim As Long position=Instr(SomeString,PartString)
If position=0 Then Return 0
While position>0
count+=1
position=Instr(position+LenP,SomeString,PartString)
Wend
Return count
End Function
Sub show(g As String,file As String,byref matches as long,minsize as long,mustdo as string)
Redim As String s()
Var L=lcase(loadfile(file))
g=lcase(g)
string_split(L,Chr(10),s())
For m As Long=minsize To len(g)
For n As Long=Lbound(s) To Ubound(s)
If Len(s(n))=m Then
For k As Long=0 To m-1
If Instr(g,Chr(s(n)[k]))=0 Then Goto lbl
Next k
If Instr(s(n),mustdo) Then
For j As Long=0 To Len(s(n))-1
If tally(s(n),Chr(s(n)[j]))>tally(g,Chr(s(n)[j])) Then Goto lbl
Next j
Print s(n)
matches+=1
End If
End If
lbl:
Next n
Next m
End Sub
dim as long matches
dim as double t=timer
show("ndeokgelw","unixdict.txt",matches,3,"k")
print
print "Overall time taken ";timer-t;" seconds"
print matches;" matches"
Sleep
|
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Pascal | Pascal |
program wu;
uses
SDL2,
math;
const
FPS = 1000 div 60;
SCALE = 6;
var
win: PSDL_Window;
ren: PSDL_Renderer;
mouse_x, mouse_y: longint;
origin: TSDL_Point;
event: TSDL_Event;
line_alpha: byte = 255;
procedure SDL_RenderDrawWuLine(renderer: PSDL_Renderer; x1, y1, x2, y2: longint);
var
r, g, b, a, a_new: Uint8;
gradient, iy: real;
x, y: longint;
px, py: plongint;
procedure swap(var a, b: longint);
var
tmp: longint;
begin
tmp := a;
a := b;
b := tmp;
end;
begin
if a = 0 then
exit;
SDL_GetRenderDrawColor(renderer, @r, @g, @b, @a);
if abs(y2 - y1) > abs(x2 - x1) then
begin
swap(x1, y1);
swap(x2, y2);
px := @y;
py := @x;
end
else
begin
px := @x;
py := @y;
end;
if x1 > x2 then
begin
swap(x1, x2);
swap(y1, y2);
end;
x := x2 - x1;
if x = 0 then
x := 1;
gradient := (y2 - y1) / x;
iy := y1;
for x := x1 to x2 do
begin
a_new := round(a * frac(iy));
y := floor(iy);
SDL_SetRenderDrawColor(renderer, r, g, b, a-a_new);
SDL_RenderDrawPoint(renderer, px^, py^);
inc(y);
SDL_SetRenderDrawColor(renderer, r, g, b, a_new);
SDL_RenderDrawPoint(renderer, px^, py^);
iy := iy + gradient;
end;
SDL_SetRenderDrawColor(renderer, r, g, b, a);
end;
begin
SDL_Init(SDL_INIT_VIDEO);
win := SDL_CreateWindow('Xiaolin Wu''s line algorithm', SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
640, 480, SDL_WINDOW_RESIZABLE);
ren := SDL_CreateRenderer(win, -1, 0);
if ren = NIL then
begin
writeln(SDL_GetError);
halt;
end;
SDL_SetRenderDrawBlendMode(ren, SDL_BLENDMODE_BLEND);
SDL_RenderSetScale(ren, SCALE, SCALE);
SDL_SetCursor(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_CROSSHAIR));
mouse_x := 0;
mouse_y := 0;
origin.x := 0;
origin.y := 0;
repeat
while SDL_PollEvent(@event) = 1 do
case event.type_ of
SDL_KEYDOWN:
if event.key.keysym.sym = SDLK_ESCAPE then
halt;
SDL_MOUSEBUTTONDOWN:
begin
origin.x := mouse_x;
origin.y := mouse_y;
end;
SDL_MOUSEMOTION:
with event.motion do
begin
mouse_x := x div SCALE;
mouse_y := y div SCALE;
end;
SDL_MOUSEWHEEL:
line_alpha := EnsureRange(line_alpha + event.wheel.y * 20, 0, 255);
SDL_QUITEV:
halt;
end;
SDL_SetRenderDrawColor(ren, 35, 35, 35, line_alpha);
SDL_RenderDrawWuLine(ren, origin.x, origin.y, mouse_x, mouse_y);
SDL_RenderPresent(ren);
SDL_SetRenderDrawColor(ren, 255, 255, 255, 255);
SDL_RenderClear(ren);
SDL_Delay(FPS);
until false;
end.
|
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #Factor | Factor | USING: sequences xml.syntax xml.writer ;
: print-character-remarks ( names remarks -- )
[ [XML <Character name=<-> ><-></Character> XML] ] 2map
[XML <CharacterRemarks><-></CharacterRemarks> XML] pprint-xml ; |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #Fantom | Fantom |
using xml
class XmlOutput
{
public static Void main ()
{
Str[] names := ["April", "Tam O'Shanter", "Emily"]
Str[] remarks := ["Bubbly: I'm > Tam and <= Emily",
"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift"]
doc := XDoc()
root := XElem("CharacterRemarks")
doc.add (root)
names.each |Str name, Int i|
{
child := XElem("Character")
child.addAttr("Name", name)
child.add(XText(remarks[i]))
root.add (child)
}
doc.write(Env.cur.out)
}
}
|
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #F.23 | F# | open System.IO
open System.Xml
open System.Xml.Linq
let xn s = XName.Get(s)
let xd = XDocument.Load(new StringReader("""
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
""")) // "
[<EntryPoint>]
let main argv =
let students = xd.Descendants <| xn "Student"
let names = students.Attributes <| xn "Name"
Seq.iter ((fun (a : XAttribute) -> a.Value) >> printfn "%s") names
0 |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Tailspin | Tailspin |
// arrays are created as literals, by simply listing elements, or by a generator expression, or a combination.
def a: [1, 2, 3..7:2, 11];
$a -> !OUT::write
'
' -> !OUT::write
// Natural indexes start at 1
$a(1) -> !OUT::write
'
' -> !OUT::write
// You can select a range
$a(3..last) -> !OUT::write
'
' -> !OUT::write
// Or a permutation/selection
$a([4,1,5]) -> !OUT::write
'
' -> !OUT::write
// Values in Tailspin are generally immutable, but there is a mutable slot in a function/templates.
// A mutable array can be appended
5 -> \(@: [1,2]; $ -> ..|@: $; $@ ! \) -> !OUT::write
|
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams.
For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage.
Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.
A win is worth three points.
A draw/tie is worth one point.
A loss is worth zero points.
Task
Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them.
Calculate the standings points for each team with each combination of outcomes.
Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.
Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?".
Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.
| #Tcl | Tcl | package require Tcl 8.6
proc groupStage {} {
foreach n {0 1 2 3} {
set points($n) {0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0}
}
set results 0
set games {0 1 0 2 0 3 1 2 1 3 2 3}
while true {
set R {0 0 1 0 2 0 3 0}
foreach r [split [format %06d $results] ""] {A B} $games {
switch $r {
2 {dict incr R $A 3}
1 {dict incr R $A; dict incr R $B}
0 {dict incr R $B 3}
}
}
foreach n {0 1 2 3} r [lsort -integer [dict values $R]] {
dict incr points($n) $r
}
if {$results eq "222222"} break
while {[regexp {[^012]} [incr results]]} continue
}
return [lmap n {3 2 1 0} {dict values $points($n)}]
}
foreach nth {First Second Third Fourth} nums [groupStage] {
puts "$nth place:\t[join [lmap n $nums {format %3s $n}] {, }]"
} |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Phix | Phix | constant x = {1, 2, 3, 1e11},
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}
integer fn = open("filename","w")
for i=1 to length(x) do
printf(fn,"%.3g\t%.5g\n",{x[i],y[i]})
end for
close(fn)
|
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #PicoLisp | PicoLisp | (setq *Xprecision 3 *Yprecision 5)
(scl 7)
(mapc
'((X Y)
(prinl
(round X *Xprecision)
" "
(round Y *Yprecision) ) )
(1.0 2.0 3.0)
(1.0 1.414213562 1.732050807) ) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #mIRC_Scripting_Language | mIRC Scripting Language | var %d = $str(0 $+ $chr(32),100), %m = 1
while (%m <= 100) {
var %n = 1
while ($calc(%n * %m) <= 100) {
var %d = $puttok(%d,$iif($gettok(%d,$calc(%n * %m),32),0,1),$calc(%n * %m),32)
inc %n
}
inc %m
}
echo -ag All Doors (Boolean): %d
var %n = 1
while (%n <= $findtok(%d,1,0,32)) {
var %t = %t $findtok(%d,1,%n,32)
inc %n
}
echo -ag Open Door Numbers: %t |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Wren | Wren | class XmlDocument {
construct new(root) {
_root = root
}
toString { "<?xml version=\"1.0\" ?>\n%(_root.toString(0))" }
}
class XmlElement {
construct new(name, text) {
_name = name
_text = text
_children = []
}
name { _name }
text { _text }
children { _children }
addChild(child) { _children.add(child) }
toString(level) {
var indent = " "
var s = indent * level + "<%(name)>\n"
if (_text != "") s = s + indent * (level + 1) + _text + "\n"
for (c in _children) {
s = s + c.toString(level+1) + "\n"
}
return s + indent * level + "</%(name)>"
}
}
var root = XmlElement.new("root", "")
var child = XmlElement.new("element", "Some text here")
root.addChild(child)
var doc = XmlDocument.new(root)
System.print(doc) |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #ContextFree | ContextFree |
startshape START
shape START {
loop i = 6 [y -1 x -1 z 10] NAME [b 1-((i+1)*0.11)]
}
shape NAME {
C [ x 34 z 1]
O [ x 46 z 2]
N [ x 64 z 3]
T [ x 85 z 4]
E [ x 95 z 5]
X [ x 106 z 6]
T [ x 125 z 7]
HYPHEN[x 135]
F [ x 145 z 8]
R [ x 158 z 9]
E [ x 175 z 10]
E [ x 188 z 11]
}
shape C {
ARCL [ y 12 flip 90 ]
ARCL [ y 12 r 180 ]
}
shape E {
LINE [ s 0.9 ]
LINE [ s 0.9 -1 y 24 ]
LINE [ s 0.4 r -90 y 0 ]
LINE [ s 0.4 r -90 y 12 ]
LINE [ s 0.4 r -90 y 24 ]
}
shape F {
LINE [ s 0.9 -1 y 24 ]
LINE [ s 0.4 r -90 y 12 ]
LINE [ s 0.4 r -90 y 24 ]
}
shape M {
LINE [ y 24 r 180 ]
LINE [ y 24 r -160 s 0.75 ]
LINE [ y 24 x 12 r 160 s 0.75 ]
LINE [ y 24 x 12 r 180 ]
}
shape N {
LINE [ y 24 r 180 ]
LINE [ y 24 r -160 ]
LINE [ y 24 x 9 r 180 ]
}
shape O {
ARCL [ y 12 flip 90]
ARCL [ y 12 r 180 ]
ARCL [ y 12 x 14 r 180 flip 90]
ARCL [ y 12 x 14 ]
}
shape R {
LINE [ s 0.9 -1 y 24 ]
LINE [ s 0.4 r -90 y 12 ]
LINE [ s 0.4 r -90 y 24 ]
LINE [ y 12 r -140 s 0.65 ]
ARCL [ y 18 x 12 r 180 flip 90 s 0.8 0.5]
ARCL [ y 18 x 12 s 0.8 0.5 ]
}
shape T {
LINE [ s 0.9 -1 y 24 ]
LINE [ s 0.4 r -90 y 24 ]
LINE [ s 0.4 r 90 y 24 ]
}
shape X {
LINE [ x 8 y 24 r 160 ]
LINE [ y 24 r -160 ]
}
shape HYPHEN{
SQUARE[y 11.5 s 4 0.5]
}
shape LINE {
TRIANGLE [[ s 1 30 y 0.26 ]]
}
shape ARCL {
SQUARE [ ]
ARCL [ size 0.97 y 0.55 r 1.5 ]
}
|
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #D | D | // Derived from AA3D - ASCII art stereogram generator
// by Jan Hubicka and Thomas Marsh
// (GNU General Public License)
// http://aa-project.sourceforge.net/aa3d/
// http://en.wikipedia.org/wiki/ASCII_stereogram
import std.stdio, std.string, std.random;
immutable image = "
111111111111111
1111111111111111
11111 1111
11111 1111
11111 1111
11111 1111
11111 1111
11111 1111
1111111111111111
111111111111111
";
void main() {
enum int width = 50;
immutable text = "DLanguage";
enum int skip = 12;
char[65536 / 2] data;
foreach (y, row; image.splitLines()) {
immutable int shift = uniform(0, int.max);
bool l = false;
foreach (x; 0 .. width) {
int s;
if (!l && x > skip) {
s = (x < row.length) ? row[x] : '\n';
if (s == ' ') {
s = 0;
} else if (s == '\n') {
s = 0;
l = true;
} else if (s >= '0' && s <= '9') {
s = '0' - s;
} else
s = -2;
} else
s = 0;
s += skip;
s = x - s;
s = (s < 0) ? text[(x + shift) % text.length] : data[s];
data[x] = cast(char)s;
write(data[x]);
}
writeln();
}
} |
http://rosettacode.org/wiki/Window_management | Window management | Treat windows or at least window identities as first class objects.
Store window identities in variables, compare them for equality.
Provide examples of performing some of the following:
hide,
show,
close,
minimize,
maximize,
move, and
resize a window.
The window of interest may or may not have been created by your program.
| #AutoHotkey | AutoHotkey | F1:: ;; when user hits the F1 key, do the following
WinGetTitle, window, A ; get identity of active window into a variable
WinMove, %window%, , 100, 100, 800, 800 ; move window to coordinates, 100, 100
; and change size to 800 x 800 pixels
sleep, 2000
WinHide, % window ; hide window
TrayTip, hidden, window is hidden, 2
sleep, 2000
WinShow, % window ; show window again
loop,
{
inputbox, name, what was the name of your window?
if (name = window) ; compare window variables for equality
{
msgbox you got it
break
}
; else try again
}
WinClose, % window
return |
http://rosettacode.org/wiki/Window_creation/X11 | Window creation/X11 | Task
Create a simple X11 application, using an X11 protocol library such as Xlib or XCB, that draws a box and "Hello World" in a window.
Implementations of this task should avoid using a toolkit as much as possible.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program creatFenX1164.s */
/* link with gcc options -lX11 -L/usr/lpp/X11/lib */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ ClientMessage, 33
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szRetourligne: .asciz "\n"
szMessErreur: .asciz "Server X11 not found.\n"
szMessErrfen: .asciz "Error create X11 window.\n"
szLibDW: .asciz "WM_DELETE_WINDOW" // message close window
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
qDisplay: .skip 8 // Display address
qDefScreen: .skip 8 // Default screen address
identWin: .skip 8 // window ident
wmDeleteMessage: .skip 16 // ident close message
stEvent: .skip 400 // provisional size
buffer: .skip 500
/**********************************************/
/* -- Code section */
/**********************************************/
.text
.global main // program entry
main:
mov x0,#0 // open server X
bl XOpenDisplay
cmp x0,#0
beq erreur
// Ok return Display address
ldr x1,qAdrqDisplay
str x0,[x1] // store Display address for future use
mov x28,x0 // and in register 28
// load default screen
ldr x2,[x0,#264] // at location 264
ldr x1,qAdrqDefScreen
str x2,[x1] //store default_screen
mov x2,x0
ldr x0,[x2,#232] // screen list
//screen areas
ldr x5,[x0,#+88] // white pixel
ldr x3,[x0,#+96] // black pixel
ldr x4,[x0,#+56] // bits par pixel
ldr x1,[x0,#+16] // root windows
// create window x11
mov x0,x28 //display
mov x2,#0 // position X
mov x3,#0 // position Y
mov x4,600 // weight
mov x5,400 // height
mov x6,0 // bordure ???
ldr x7,0 // ?
ldr x8,qBlanc // background
str x8,[sp,-16]! // argument fot stack
bl XCreateSimpleWindow
add sp,sp,16 // for stack alignement
cmp x0,#0 // error ?
beq erreurF
//mov x3,sp
ldr x1,qAdridentWin
str x0,[x1] // store window ident for future use
mov x27,x0 // and in register 27
// Correction of window closing error
mov x0,x28 // Display address
ldr x1,qAdrszLibDW // atom name address
mov x2,#1 // False create atom if not exist
bl XInternAtom
cmp x0,#0
ble erreurF
ldr x1,qAdrwmDeleteMessage // address message
str x0,[x1]
mov x2,x1 // address atom create
mov x0,x28 // display address
mov x1,x27 // window ident
mov x3,#1 // number of protocoles
bl XSetWMProtocols
cmp x0,#0
ble erreurF
// Display window
mov x1,x27 // ident window
mov x0,x28 // Display address
bl XMapWindow
1: // events loop
mov x0,x28 // Display address
ldr x1,qAdrstEvent // events structure address
bl XNextEvent
ldr x0,qAdrstEvent // events structure address
ldr w0,[x0] // type in 4 fist bytes
cmp w0,#ClientMessage // message for close window
bne 1b // no -> loop
ldr x0,qAdrstEvent // events structure address
ldr x1,[x0,56] // location message code
ldr x2,qAdrwmDeleteMessage // equal ?
ldr x2,[x2]
cmp x1,x2
bne 1b // no loop
mov x0,0 // end Ok
b 100f
erreurF: // error create window
ldr x0,qAdrszMessErrfen
bl affichageMess
mov x0,1
b 100f
erreur: // error no server x11 active
ldr x0,qAdrszMessErreur
bl affichageMess
mov x0,1
100: // program standard end
mov x8,EXIT
svc 0
qBlanc: .quad 0xF0F0F0F0
qAdrqDisplay: .quad qDisplay
qAdrqDefScreen: .quad qDefScreen
qAdridentWin: .quad identWin
qAdrstEvent: .quad stEvent
qAdrszMessErrfen: .quad szMessErrfen
qAdrszMessErreur: .quad szMessErreur
qAdrwmDeleteMessage: .quad wmDeleteMessage
qAdrszLibDW: .quad szLibDW
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Wilson_primes_of_order_n | Wilson primes of order n | Definition
A Wilson prime of order n is a prime number p such that p2 exactly divides:
(n − 1)! × (p − n)! − (− 1)n
If n is 1, the latter formula reduces to the more familiar: (p - n)! + 1 where the only known examples for p are 5, 13, and 563.
Task
Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18 or,
if your language supports big integers, for p < 11,000.
Related task
Primality by Wilson's theorem
| #ALGOL_68 | ALGOL 68 | BEGIN # find Wilson primes of order n, primes such that: #
# ( ( n - 1 )! x ( p - n )! - (-1)^n ) mod p^2 = 0 #
INT limit = 5 508; # max prime to consider #
# Build list of primes. #
[]INT primes =
BEGIN
# sieve the primes to limit^2 which will hopefully be enough for primes #
[ 1 : limit * limit ]BOOL prime;
prime[ 1 ] := FALSE; prime[ 2 ] := TRUE;
FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE OD;
FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD;
FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO
IF prime[ i ] THEN FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD FI
OD;
# count the primes up to the limit #
INT p count := 0; FOR i TO limit DO IF prime[ i ] THEN p count +:= 1 FI OD;
# construct a list of the primes #
[ 1 : p count ]INT primes;
INT p pos := 0;
FOR i WHILE p pos < UPB primes DO IF prime[ i ] THEN primes[ p pos +:= 1 ] := i FI OD;
primes
END;
# Build list of factorials. #
PR precision 20000 PR # set the number of digits for a LONG LONG INT #
[ 0 : primes[ UPB primes ] ]LONG LONG INT facts;
facts[ 0 ] := 1; FOR i TO UPB facts DO facts[ i ] := facts[ i - 1 ] * i OD;
# find the Wilson primes #
INT sign := 1;
print( ( " n: Wilson primes", newline ) );
print( ( "-----------------", newline ) );
FOR n TO 11 DO
print( ( whole( n, -2 ), ":" ) );
sign := - sign;
LONG LONG INT f n minus 1 = facts[ n - 1 ];
FOR p pos FROM LWB primes TO UPB primes DO
INT p = primes[ p pos ];
IF p >= n THEN
LONG LONG INT f = f n minus 1 * facts[ p - n ] - sign;
IF f MOD ( p * p ) = 0 THEN print( ( " ", whole( p, 0 ) ) ) FI
FI
OD;
print( ( newline ) )
OD
END |
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may overlap but are not allowed to zigzag, or wrap around.
Task
Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.
The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message.
Pack a minimum of 25 words into the grid.
Print the resulting grid and the solutions.
Example
0 1 2 3 4 5 6 7 8 9
0 n a y r y R e l m f
1 y O r e t s g n a g
2 t n e d i S k y h E
3 n o t n c p c w t T
4 a l s u u n T m a x
5 r o k p a r i s h h
6 a A c f p a e a c C
7 u b u t t t O l u n
8 g y h w a D h p m u
9 m i r p E h o g a n
parish (3,5)(8,5) gangster (9,1)(2,1)
paucity (4,6)(4,0) guaranty (0,8)(0,1)
prim (3,9)(0,9) huckster (2,8)(2,1)
plasm (7,8)(7,4) fancy (3,6)(7,2)
hogan (5,9)(9,9) nolo (1,2)(1,5)
under (3,4)(3,0) chatham (8,6)(8,0)
ate (4,8)(6,6) nun (9,7)(9,9)
butt (1,7)(4,7) hawk (9,5)(6,2)
why (3,8)(1,8) ryan (3,0)(0,0)
fay (9,0)(7,2) much (8,8)(8,5)
tar (5,7)(5,5) elm (6,0)(8,0)
max (7,4)(9,4) pup (5,3)(3,5)
mph (8,8)(6,8)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC | Randomize Timer ' OK getting a good puzzle every time
#Macro TrmSS (n)
LTrim(Str(n))
#EndMacro
'overhauled
Dim Shared As ULong LengthLimit(3 To 10) 'reset in Initialize, track and limit longer words
'LoadWords opens file of words and sets
Dim Shared As ULong NWORDS 'set in LoadWords, number of words with length: > 2 and < 11 and just letters
' word file words (shuffled) to be fit into puzzle and index position
Dim Shared As String WORDSSS(1 To 24945), CWORDSSS(1 To 24945)
Dim Shared As ULong WORDSINDEX 'the file has 24945 words but many are unsuitable
'words placed in Letters grid, word itself (WSS) x, y head (WX, WY) and direction (WD), WI is the index to all these
Dim Shared As String WSS(1 To 100)
Dim Shared As ULong WX(1 To 100), WY(1 To 100), WD(1 To 100), WI
' letters grid and direction arrays
Dim Shared As String LSS(0 To 9, 0 To 9)
Dim Shared As Long DX(0 To 7), DY(0 To 7)
DX(0) = 1: DY(0) = 0
DX(1) = 1: DY(1) = 1
DX(2) = 0: DY(2) = 1
DX(3) = -1: DY(3) = 1
DX(4) = -1: DY(4) = 0
DX(5) = -1: DY(5) = -1
DX(6) = 0: DY(6) = -1
DX(7) = 1: DY(7) = -1
'to store all the words found embedded in the grid LSS()
Dim Shared As String ALLSS(1 To 200)
Dim Shared As ULong AllX(1 To 200), AllY(1 To 200), AllD(1 To 200) 'to store all the words found embedded in the grid LSS()
Dim Shared As ULong ALLindex
' signal successful fill of puzzle
Dim Shared FILLED As Boolean
Dim Shared As ULong try = 1
Sub LoadWords
Dim As String wdSS
Dim As ULong i, m, ff = FreeFile
Dim ok As Boolean
Open "unixdict.txt" For Input As #ff
If Err > 0 Then
Print !"\n unixdict.txt not found, program will end"
Sleep 5000
End
End If
While Eof(1) = 0
Input #ff, wdSS
If Len(wdSS) > 2 And Len(wdSS) < 11 Then
ok = TRUE
For m = 1 To Len(wdSS)
If Asc(wdSS, m) < 97 Or Asc(wdSS, m) > 122 Then ok = FALSE: Exit For
Next
If ok Then i += 1: WORDSSS(i) = wdSS: CWORDSSS(i) = wdSS
End If
Wend
Close #ff
NWORDS = i
End Sub
Sub Shuffle
Dim As ULong i, r
For i = NWORDS To 2 Step -1
r = Int(Rnd * i) + 1
Swap WORDSSS(i), WORDSSS(r)
Next
End Sub
Sub Initialize
Dim As ULong r, c'', x, y, d
Dim As String wdSS
FILLED = FALSE
For r = 0 To 9
For c = 0 To 9
LSS(c, r) = " "
Next
Next
'reset word arrays by resetting the word index back to zero
WI = 0
'fun stuff for me but doubt others would like that much fun!
'pluggin "basic", 0, 0, 2
'pluggin "plus", 1, 0, 0
'to assure the spreading of ROSETTA CODE
LSS(Int(Rnd * 5) + 5, 0) = "R": LSS(Int(Rnd * 9) + 1, 1) = "O"
LSS(Int(Rnd * 9) + 1, 2) = "S": LSS(Int(Rnd * 9) + 1, 3) = "E"
LSS(1, 4) = "T": LSS(9, 4) = "T": LSS(Int(10 * Rnd), 5) = "A"
LSS(Int(10 * Rnd), 6) = "C": LSS(Int(10 * Rnd), 7) = "O"
LSS(Int(10 * Rnd), 8) = "D": LSS(Int(10 * Rnd), 9) = "E"
'reset limits
LengthLimit(3) = 200
LengthLimit(4) = 6
LengthLimit(5) = 3
LengthLimit(6) = 2
LengthLimit(7) = 1
LengthLimit(8) = 0
LengthLimit(9) = 0
LengthLimit(10) = 0
'reset word order
Shuffle
End Sub
'for fun plug-in of words
Sub pluggin (wdSS As String, x As Long, y As Long, d As Long)
For i As ULong = 0 To Len(wdSS) - 1
LSS(x + i * DX(d), y + i * DY(d)) = Mid(wdSS, i + 1, 1)
Next
WI += WI
WSS(WI) = wdSS: WX(WI) = x: WY(WI) = y: WD(WI) = d
End Sub
' Function TrmSS (n As Integer) As String
' TrmSS = RTrim(LTrim(Str(n)))
' End Function
'used in PlaceWord
Function CountSpaces () As ULong
Dim As ULong x, y, count
For y = 0 To 9
For x = 0 To 9
If LSS(x, y) = " " Then count += 1
Next
Next
CountSpaces = count
End Function
Sub ShowPuzzle
Dim As ULong i, x, y
'Dim As String wateSS
Cls
Print " 0 1 2 3 4 5 6 7 8 9"
Locate 3, 1
For i = 0 To 9
Print TrmSS(i)
Next
For y = 0 To 9
For x = 0 To 9
Locate y + 3, 2 * x + 5: Print LSS(x, y)
Next
Next
For i = 1 To WI
If i < 21 Then
Locate i + 1, 30: Print TrmSS(i); " "; WSS(i)
ElseIf i < 41 Then
Locate i - 20 + 1, 45: Print TrmSS(i); " "; WSS(i)
ElseIf i < 61 Then
Locate i - 40 + 1, 60: Print TrmSS(i); " "; WSS(i)
End If
Next
Locate 18, 1: Print "Spaces left:"; CountSpaces
Locate 19, 1: Print NWORDS
Locate 20, 1: Print Space(16)
If WORDSINDEX Then Locate 20, 1: Print TrmSS(WORDSINDEX); " "; WORDSSS(WORDSINDEX)
'LOCATE 15, 1: INPUT "OK, press enter... "; wateSS
End Sub
'used in PlaceWord
Function Match (word As String, template As String) As Long
Dim i As ULong
Dim c As String
Match = 0
If Len(word) <> Len(template) Then Exit Function
For i = 1 To Len(template)
If Asc(template, i) <> 32 And (Asc(word, i) <> Asc(template, i)) Then Exit Function
Next
Match = -1
End Function
'heart of puzzle builder
Sub PlaceWord
' place the words randomly in the grid
' start at random spot and work forward or back 100 times = all the squares
' for each open square try the 8 directions for placing the word
' even if word fits Rossetta Challenge task requires leaving 11 openings to insert ROSETTA CODE,
' exactly 11 spaces needs to be left, if/when this occurs FILLED will be set true to signal finished to main loop
' if place a word update LSS, WI, WSS(WI), WX(WI), WY(WI), WD(WI)
Dim As String wdSS, templateSS
Dim As Long rdir
Dim As ULong wLen, spot, testNum
Dim As ULong x, y, d, dNum, rdd, i, j
Dim As Boolean b1, b2
wdSS = WORDSSS(WORDSINDEX) ' the right side is all shared
' skip too many long words
If LengthLimit(Len(wdSS)) Then LengthLimit(Len(wdSS)) += 1 Else Exit Sub 'skip long ones
wLen = Len(wdSS) - 1 ' from the spot there are this many letters to check
spot = Int(Rnd * 100) ' a random spot on grid
testNum = 1 ' when this hits 100 we've tested all possible spots on grid
If Rnd < .5 Then rdir = -1 Else rdir = 1 ' go forward or back from spot for next test
While testNum < 101
y = spot \ 10
x = spot Mod 10
If LSS(x, y) = Mid(wdSS, 1, 1) Or LSS(x, y) = " " Then
d = Int(8 * Rnd)
If Rnd < .5 Then rdd = -1 Else rdd = 1
dNum = 1
While dNum < 9
'will wdSS fit? from at x, y
templateSS = ""
b1 = wLen * DX(d) + x >= 0 And wLen * DX(d) + x <= 9
b2 = wLen * DY(d) + y >= 0 And wLen * DY(d) + y <= 9
If b1 And b2 Then 'build the template of letters and spaces from Letter grid
For i = 0 To wLen
templateSS += LSS(x + i * DX(d), y + i * DY(d))
Next
If Match(wdSS, templateSS) Then 'the word will fit but does it fill anything?
For j = 1 To Len(templateSS)
If Asc(templateSS, j) = 32 Then 'yes a space to fill
For i = 0 To wLen
LSS(x + i * DX(d), y + i * DY(d)) = Mid(wdSS, i + 1, 1)
Next
WI += 1
WSS(WI) = wdSS: WX(WI) = x: WY(WI) = y: WD(WI) = d
ShowPuzzle
If CountSpaces = 0 Then FILLED = TRUE
Exit Sub 'get out now that word is loaded
End If
Next
'if still here keep looking
End If
End If
d = (d + 8 + rdd) Mod 8
dNum += 1
Wend
End If
spot = (spot + 100 + rdir) Mod 100
testNum += 1
Wend
End Sub
Sub FindAllWords
Dim As String wdSS, templateSS, wateSS
Dim As ULong wLen, x, y, d, j
Dim As Boolean b1, b2
For i As ULong = 1 To NWORDS
wdSS = CWORDSSS(i)
wLen = Len(wdSS) - 1
For y = 0 To 9
For x = 0 To 9
If LSS(x, y) = Mid(wdSS, 1, 1) Then
For d = 0 To 7
b1 = wLen * DX(d) + x >= 0 And wLen * DX(d) + x <= 9
b2 = wLen * DY(d) + y >= 0 And wLen * DY(d) + y <= 9
If b1 And b2 Then 'build the template of letters and spaces from Letter grid
templateSS = ""
For j = 0 To wLen
templateSS += LSS(x + j * DX(d), y + j * DY(d))
Next
If templateSS = wdSS Then 'found a word
'store it
ALLindex += 1
ALLSS(ALLindex) = wdSS: AllX(ALLindex) = x: AllY(ALLindex) = y: AllD(ALLindex) = d
'report it
Locate 22, 1: Print Space(50)
Locate 22, 1: Print "Found: "; wdSS; " ("; TrmSS(x); ", "; TrmSS(y); ") >>>---> "; TrmSS(d);
Input " Press enter...", wateSS
End If
End If
Next
End If
Next
Next
Next
End Sub
Sub FilePuzzle
Dim As ULong i, r, c, ff = FreeFile
Dim As String bSS
Open "WS Puzzle.txt" For Output As #ff
Print #ff, " 0 1 2 3 4 5 6 7 8 9"
Print #ff,
For r = 0 To 9
bSS = TrmSS(r) + " "
For c = 0 To 9
bSS += LSS(c, r) + " "
Next
Print #ff, bSS
Next
Print #ff,
Print #ff, "Directions >>>---> 0 = East, 1 = SE, 2 = South, 3 = SW, 4 = West, 5 = NW, 6 = North, 7 = NE"
Print #ff,
Print #ff, " These are the items from unixdict.txt used to build the puzzle:"
Print #ff,
For i = 1 To WI Step 2
Print #ff, Right(Space(7) + TrmSS(i), 7); ") "; Right(Space(7) + WSS(i), 10); " ("; TrmSS(WX(i)); ", "; TrmSS(WY(i)); ") >>>---> "; TrmSS(WD(i));
If i + 1 <= WI Then
Print #ff, Right(Space(7) + TrmSS(i + 1), 7); ") "; Right(Space(7) + WSS(i + 1), 10); " ("; TrmSS(WX(i + 1)); ", "; TrmSS(WY(i + 1)); ") >>>---> "; TrmSS(WD(i + 1))
Else
Print #ff,
End If
Next
Print #ff,
Print #ff, " These are the items from unixdict.txt found embedded in the puzzle:"
Print #ff,
For i = 1 To ALLindex Step 2
Print #ff, Right(Space(7) + TrmSS(i), 7); ") "; Right(Space(7) + ALLSS(i), 10); " ("; TrmSS(AllX(i)); ", "; TrmSS(AllY(i)); ") >>>---> "; TrmSS(AllD(i));
If i + 1 <= ALLindex Then
Print #ff, Right(Space(7) + TrmSS(i + 1), 7); ") "; Right(Space(7) + ALLSS(i + 1), 10); " ("; TrmSS(AllX(i + 1)); ", "; TrmSS(AllY(i + 1)); ") >>>---> "; TrmSS(AllD(i + 1))
Else
Print #ff, ""
End If
Next
Print #ff,
Print #ff, "On try #" + TrmSS(try) + " a successful puzzle was built and filed."
Close #ff
End Sub
LoadWords 'this sets NWORDS count to work with
While try < 11
Initialize
ShowPuzzle
For WORDSINDEX = 1 To NWORDS
PlaceWord
' ShowPuzzle
If FILLED Then Exit For
Next
If Not filled And WI > 24 Then ' we have 25 or more words
For y As ULong = 0 To 9 ' fill spaces with random letters
For x As ULong = 0 To 9
If LSS(x, y) = " " Then LSS(x, y) = Chr(Int(Rnd * 26) + 1 + 96)
Next
Next
filled = TRUE
ShowPuzzle
End If
If FILLED And WI > 24 Then
FindAllWords
FilePuzzle
Locate 23, 1: Print "On try #"; TrmSS(try); " a successful puzzle was built and filed."
Exit While
Else
try += 1
End If
Wend
If Not FILLED Then Locate 23, 1: Print "Sorry, 10 tries and no success."
Sleep
End |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #AWK | AWK | function wordwrap_paragraph(p)
{
if ( length(p) < 1 ) return
split(p, words)
spaceLeft = lineWidth
line = words[1]
delete words[1]
for (i = 1; i <= length(words); i++) {
word = words[i]
if ( (length(word) + 1) > spaceLeft ) {
print line
line = word
spaceLeft = lineWidth - length(word)
} else {
spaceLeft -= length(word) + 1
line = line " " word
}
}
print line
}
BEGIN {
lineWidth = width
par = ""
}
/^[ \t]*$/ {
wordwrap_paragraph(par)
par = ""
}
!/^[ \t]*$/ {
par = par " " $0
}
END {
wordwrap_paragraph(par)
} |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
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
| #jq | jq | def count(stream): reduce stream as $i (0; .+1);
def words: [inputs]; # one way to read the word list
def oneAway($a; $b):
($a|explode) as $ax
| ($b|explode) as $bx
| 1 == count(range(0; $a|length) | select($ax[.] != $bx[.]));
# input: the word list
def wordLadder($a; $b):
($a|length) as $len
| { poss: map(select(length == $len)), # the relevant words
todo: [[$a]] # possible chains
}
| until ( ((.todo|length) == 0) or .solution;
.curr = .todo[0]
| .todo |= .[1:]
| .curr[-1] as $c
| (.poss | map(select( oneAway(.; $c) ))) as $next
| if ($b | IN($next[]))
then .curr += [$b]
| .solution = (.curr|join(" -> "))
else .poss = (.poss - $next)
| .curr as $curr
| .todo = (reduce range(0; $next|length) as $i (.todo;
. + [$curr + [$next[$i] ]] ))
end )
| if .solution then .solution
else "There is no ladder from \($a) to \($b)."
end ;
def pairs:
["boy", "man"],
["girl", "lady"],
["john", "jane"],
["child", "adult"],
["word", "play"]
;
words
| pairs as $p
| wordLadder($p[0]; $p[1]) |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
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
| #Julia | Julia | const dict = Set(split(read("unixdict.txt", String), r"\s+"))
function targeted_mutations(str::AbstractString, target::AbstractString)
working, tried = [[str]], Set{String}()
while all(a -> a[end] != target, working)
newworking = Vector{Vector{String}}()
for arr in working
s = arr[end]
push!(tried, s)
for j in 1:length(s), c in 'a':'z'
w = s[1:j-1] * c * s[j+1:end]
if w in dict && !(w in tried)
push!(newworking, [arr; w])
end
end
end
isempty(newworking) && return [["This cannot be done."]]
working = newworking
end
return filter(a -> a[end] == target, working)
end
println("boy to man: ", targeted_mutations("boy", "man"))
println("girl to lady: ", targeted_mutations("girl", "lady"))
println("john to jane: ", targeted_mutations("john", "jane"))
println("child to adult: ", targeted_mutations("child", "adult"))
|
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[3]]]]];
sel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&];
g=Graph[db,UndirectedEdge@@@sel];
FindShortestPath[g,"boy","man"]
db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[4]]]]];
sel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&];
g=Graph[db,UndirectedEdge@@@sel];
FindShortestPath[g,"girl","lady"]
FindShortestPath[g,"john","jane"]
db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[5]]]]];
sel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&];
g=Graph[db,UndirectedEdge@@@sel];
FindShortestPath[g,"child","adult"] |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the wheel or grid. Usually there will be a minimum word length of 3 or 4
characters. Each letter may only be used as many times as it appears in the wheel
or grid.
An example
N
D
E
O
K
G
E
L
W
Task
Write a program to solve the above "word wheel" puzzle.
Specifically:
Find all words of 3 or more letters using only the letters in the string ndeokgelw.
All words must contain the central letter K.
Each letter may be used only as many times as it appears in the string.
For this task we'll use lowercase English letters exclusively.
A "word" is defined to be any string contained in the file located at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt.
If you prefer to use a different dictionary, please state which one you have used.
Optional extra
Word wheel puzzles usually state that there is at least one nine-letter word to be found.
Using the above dictionary, find the 3x3 grids with at least one nine-letter
solution that generate the largest number of words of three or more letters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
)
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
letters := "deegklnow"
wordsAll := bytes.Split(b, []byte{'\n'})
// get rid of words under 3 letters or over 9 letters
var words [][]byte
for _, word := range wordsAll {
word = bytes.TrimSpace(word)
le := len(word)
if le > 2 && le < 10 {
words = append(words, word)
}
}
var found []string
for _, word := range words {
le := len(word)
if bytes.IndexByte(word, 'k') >= 0 {
lets := letters
ok := true
for i := 0; i < le; i++ {
c := word[i]
ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })
if ix < len(lets) && lets[ix] == c {
lets = lets[0:ix] + lets[ix+1:]
} else {
ok = false
break
}
}
if ok {
found = append(found, string(word))
}
}
}
fmt.Println("The following", len(found), "words are the solutions to the puzzle:")
fmt.Println(strings.Join(found, "\n"))
// optional extra
mostFound := 0
var mostWords9 []string
var mostLetters []byte
// extract 9 letter words
var words9 [][]byte
for _, word := range words {
if len(word) == 9 {
words9 = append(words9, word)
}
}
// iterate through them
for _, word9 := range words9 {
letterBytes := make([]byte, len(word9))
copy(letterBytes, word9)
sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })
// get distinct bytes
distinctBytes := []byte{letterBytes[0]}
for _, b := range letterBytes[1:] {
if b != distinctBytes[len(distinctBytes)-1] {
distinctBytes = append(distinctBytes, b)
}
}
distinctLetters := string(distinctBytes)
for _, letter := range distinctLetters {
found := 0
letterByte := byte(letter)
for _, word := range words {
le := len(word)
if bytes.IndexByte(word, letterByte) >= 0 {
lets := string(letterBytes)
ok := true
for i := 0; i < le; i++ {
c := word[i]
ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })
if ix < len(lets) && lets[ix] == c {
lets = lets[0:ix] + lets[ix+1:]
} else {
ok = false
break
}
}
if ok {
found = found + 1
}
}
}
if found > mostFound {
mostFound = found
mostWords9 = []string{string(word9)}
mostLetters = []byte{letterByte}
} else if found == mostFound {
mostWords9 = append(mostWords9, string(word9))
mostLetters = append(mostLetters, letterByte)
}
}
}
fmt.Println("\nMost words found =", mostFound)
fmt.Println("Nine letter words producing this total:")
for i := 0; i < len(mostWords9); i++ {
fmt.Println(mostWords9[i], "with central letter", string(mostLetters[i]))
}
} |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Perl | Perl | #!perl
use strict;
use warnings;
sub plot {
my ($x, $y, $c) = @_;
printf "plot %d %d %.1f\n", $x, $y, $c if $c;
}
sub ipart {
int shift;
}
sub round {
int( 0.5 + shift );
}
sub fpart {
my $x = shift;
$x - int $x;
}
sub rfpart {
1 - fpart(shift);
}
sub drawLine {
my ($x0, $y0, $x1, $y1) = @_;
my $plot = \&plot;
if( abs($y1 - $y0) > abs($x1 - $x0) ) {
$plot = sub { plot( @_[1, 0, 2] ) };
($x0, $y0, $x1, $y1) = ($y0, $x0, $y1, $x1);
}
if( $x0 > $x1 ) {
($x0, $x1, $y0, $y1) = ($x1, $x0, $y1, $y0);
}
my $dx = $x1 - $x0;
my $dy = $y1 - $y0;
my $gradient = $dy / $dx;
my @xends;
my $intery;
# handle the endpoints
for my $xy ([$x0, $y0], [$x1, $y1]) {
my ($x, $y) = @$xy;
my $xend = round($x);
my $yend = $y + $gradient * ($xend - $x);
my $xgap = rfpart($x + 0.5);
my $x_pixel = $xend;
my $y_pixel = ipart($yend);
push @xends, $x_pixel;
$plot->($x_pixel, $y_pixel , rfpart($yend) * $xgap);
$plot->($x_pixel, $y_pixel+1, fpart($yend) * $xgap);
next if defined $intery;
# first y-intersection for the main loop
$intery = $yend + $gradient;
}
# main loop
for my $x ( $xends[0] + 1 .. $xends[1] - 1 ) {
$plot->($x, ipart ($intery), rfpart($intery));
$plot->($x, ipart ($intery)+1, fpart($intery));
$intery += $gradient;
}
}
if( $0 eq __FILE__ ) {
drawLine( 0, 1, 10, 2 );
}
__END__
|
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #Forth | Forth | include ffl/est.fs
include ffl/xos.fs
\ Input lists
0 value names
here ," Emily"
here ," Tam O'Shanter"
here ," April"
here to names
, , ,
0 value remarks
here ," Short & shrift"
here ,\" Burns: \"When chapman billies leave the street ...\""
here ," Bubbly: I'm > Tam and <= Emily"
here to remarks
, , ,
: s++ ( c-addr1 -- c-addr2 c-addr3 u3 )
dup cell+ swap @ count
;
\ Create xml writer
tos-create xml
: create-xml ( c-addr1 c-addr2 -- )
0 s" CharacterRemarks" xml xos-write-start-tag
3 0 DO
swap s++ s" name" 2swap 1
s" Character" xml xos-write-start-tag
swap s++ xml xos-write-text
s" Character" xml xos-write-end-tag
LOOP
drop drop
s" CharacterRemarks" xml xos-write-end-tag
;
names remarks create-xml
\ Output xml string
xml str-get type cr |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Factor | Factor | USING: io multiline sequences xml xml.data xml.traversal ;
: print-student-names ( string -- )
string>xml "Student" tags-named [ "Name" attr print ] each ;
[[ <Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>]] print-student-names |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Fantom | Fantom |
using xml
class XmlInput
{
public static Void main ()
{
// create the XML parser
parser := XParser(File("sample-xml.xml".toUri).in)
// parse the document, creating an XML document
XDoc doc := parser.parseDoc
// walk through each child element from the root of the document
doc.root.elems.each |elem|
{
// printing the Name attribute of all Students
if (elem.name == "Student") { echo (elem.get("Name")) }
}
}
}
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Tcl | Tcl | set ary {}
lappend ary 1
lappend ary 3
lset ary 0 2
puts [lindex $ary 0] |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams.
For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage.
Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.
A win is worth three points.
A draw/tie is worth one point.
A loss is worth zero points.
Task
Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them.
Calculate the standings points for each team with each combination of outcomes.
Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.
Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?".
Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Dim games As New List(Of String) From {"12", "13", "14", "23", "24", "34"}
Dim results = "000000"
Function FromBase3(num As String) As Integer
Dim out = 0
For Each c In num
Dim d = Asc(c) - Asc("0"c)
out = 3 * out + d
Next
Return out
End Function
Function ToBase3(num As Integer) As String
Dim ss As New StringBuilder
While num > 0
Dim re = num Mod 3
num \= 3
ss.Append(re)
End While
Return New String(ss.ToString().Reverse().ToArray())
End Function
Function NextResult() As Boolean
If results = "222222" Then
Return False
End If
Dim res = FromBase3(results)
Dim conv = ToBase3(res + 1)
results = conv.PadLeft(6, "0"c)
Return True
End Function
Sub Main()
Dim points(0 To 3, 0 To 9) As Integer
Do
Dim records(0 To 3) As Integer
For index = 0 To games.Count - 1
Select Case results(index)
Case "2"c
records(Asc(games(index)(0)) - Asc("1"c)) += 3
Case "1"c
records(Asc(games(index)(0)) - Asc("1"c)) += 1
records(Asc(games(index)(1)) - Asc("1"c)) += 1
Case "0"c
records(Asc(games(index)(1)) - Asc("1"c)) += 3
End Select
Next
Array.Sort(records)
For index = 0 To records.Length - 1
Dim t = records(index)
points(index, t) += 1
Next
Loop While NextResult()
Console.WriteLine("POINTS 0 1 2 3 4 5 6 7 8 9")
Console.WriteLine("-------------------------------------------------------------")
Dim places As New List(Of String) From {"1st", "2nd", "3rd", "4th"}
For i = 0 To places.Count - 1
Console.Write("{0} place", places(i))
For j = 0 To 9
Console.Write("{0,5}", points(3 - i, j))
Next
Console.WriteLine()
Next
End Sub
End Module |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #PL.2FI | PL/I | *Process source attributes xref;
aaa: Proc Options(main);
declare X(5) float (9) initial (1, 2, 3, 4, 5),
Y(5) float (18) initial (9, 8, 7, 6, 1e9);
declare (x_precision, y_precision) fixed binary;
Dcl out stream output;
open file(out) title('/OUT.TXT,type(text),recsize(100)');
x_precision = 9;
y_precision = 16;
put file(out) edit((X(i),Y(i) do i=1 to 5))
(skip,e(19,x_precision),
x(2),e(24,y_precision));
end; |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #PowerShell | PowerShell | $x = @(1, 2, 3, 1e11)
$y = @(1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791)
$xprecision = 3
$yprecision = 5
$arr = foreach($i in 0..($x.count-1)) {
[pscustomobject]@{x = "{0:g$xprecision}" -f $x[$i]; y = "{0:g$yprecision}" -f $y[$i]}
}
($arr | format-table -HideTableHeaders | Out-String).Trim() > filename.txt
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #ML.2FI | ML/I | MCSKIP "WITH" NL
"" 100 doors
MCINS %.
MCSKIP MT,<>
"" Doors represented by P1-P100, 0 is closed
MCPVAR 100
"" Set P variables to 0
MCDEF ZEROPS WITHS NL AS <MCSET T1=1
%L1.MCSET PT1=0
MCSET T1=T1+1
MCGO L1 UNLESS T1 EN 101
>
ZEROPS
"" Generate door state
MCDEF STATE WITHS () AS <MCSET T1=%A1.
MCGO L1 UNLESS T1 EN 0
closed<>MCGO L0
%L1.open>
"" Main macro - no arguments
"" T1 is pass number
"" T2 is door number
MCDEF DOORS WITHS NL
AS <MCSET T1=1
"" pass loop
%L1.MCGO L4 IF T1 GR 100
"" door loop
MCSET T2=T1
%L2.MCGO L3 IF T2 GR 100
MCSET PT2=1-PT2
MCSET T2=T2+T1
MCGO L2
%L3.MCSET T1=T1+1
MCGO L1
%L4."" now output the result
MCSET T1=1
%L5.door %T1. is STATE(%PT1.)
MCSET T1=T1+1
MCGO L5 UNLESS T1 GR 100
>
"" Do it
DOORS |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.