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/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Lasso | Lasso | // Define the thread if it doesn't exist
// New definition supersede any current threads.
not ::serverwide_singleton->istype
? define serverwide_singleton => thread {
data public switch = 'x'
}
local(
a = serverwide_singleton,
b = serverwide_singleton,
)
#a->switch = 'a'
#b->switch = 'b'
#a->switch // b |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Latitude | Latitude | Singleton ::= Object clone tap {
self id := 0.
self newID := {
self id := self id + 1.
}.
self clone := {
err ArgError clone tap { self message := "Singleton object!". } throw.
}.
}.
println: Singleton newID. ; 1
println: Singleton newID. ; 2
println: Singleton newID. ; 3 |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Racket | Racket |
#lang racket
(define (bubble-sort <? v)
(define len (vector-length v))
(define ref vector-ref)
(let loop ([max len]
[again? #f])
(for ([i (in-range 0 (- max 1))]
[j (in-range 1 max)])
(define vi (ref v i))
(when (<? (ref v j) vi)
(vector-set! v i (ref v j))
(vector-set! v j vi)
(set! again? #t)))
(when again? (loop (- max 1) #f)))
v)
|
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Lingo | Lingo | -- parent script "SingletonDemo"
property _instance
property _someProperty
----------------------------------------
-- @constructor
----------------------------------------
on new (me)
if not voidP(me.script._instance) then return me.script._instance
me.script._instance = me
me._someProperty = 0
return me
end
----------------------------------------
-- sample method
----------------------------------------
on someMethod (me, x)
me._someProperty = me._someProperty + x
return me._someProperty
end |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Logtalk | Logtalk | :- object(singleton).
:- public(value/1).
value(Value) :-
state(Value).
:- public(set_value/1).
set_value(Value) :-
retract(state(_)),
assertz(state(Value)).
:- private(state/1).
:- dynamic(state/1).
state(0).
:- end_object. |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Raku | Raku | sub bubble_sort (@a) {
for ^@a -> $i {
for $i ^..^ @a -> $j {
@a[$j] < @a[$i] and @a[$i, $j] = @a[$j, $i];
}
}
} |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
import java.util.random
class RCSingleton public
method main(args = String[]) public static
RCSingleton.Testcase.main(args)
return
-- ---------------------------------------------------------------------------
class RCSingleton.Instance public
properties private static
_instance = Instance()
properties private
_refCount = int
_random = Random
method Instance() private
this._refCount = 0
this._random = Random()
return
method getInstance public static returns RCSingleton.Instance
return _instance
method getRandom public returns Random
return _random
method addRef public protect
_refCount = _refCount + 1
return
method release public protect
if _refCount > 0 then
_refCount = _refCount - 1
return
method getRefCount public protect returns int
return _refCount
-- ---------------------------------------------------------------------------
class RCSingleton.Testcase public implements Runnable
properties private
_instance = RCSingleton.Instance
method run public
say threadInfo'|-'
thud = Thread.currentThread
_instance = RCSingleton.Instance.getInstance
thud.yield
_instance.addRef
say threadInfo'|'_instance.getRefCount
thud.yield
do
thud.sleep(_instance.getRandom.nextInt(1000))
catch ex = InterruptedException
ex.printStackTrace
end
_instance.release
say threadInfo'|'_instance.getRefCount
return
method main(args = String[]) public static
threads = [ Thread -
Thread(Testcase()), Thread(Testcase()), Thread(Testcase()), -
Thread(Testcase()), Thread(Testcase()), Thread(Testcase()) ]
say threadInfo'|-'
mn = Testcase()
mn._instance = RCSingleton.Instance.getInstance
say mn.threadInfo'|'mn._instance.getRefCount
mn._instance.addRef
say mn.threadInfo'|'mn._instance.getRefCount
do
loop tr over threads
(Thread tr).start
end tr
Thread.sleep(400)
catch ex = InterruptedException
ex.printStackTrace
end
mn._instance.release
say mn.threadInfo'|'mn._instance.getRefCount
return
method threadInfo public static returns String
trd = Thread.currentThread
tid = trd.getId
hc = trd.hashCode
info = Rexx(trd.getName).left(16, '_')':' -
|| Rexx(Long.toString(tid)).right(10, 0)':' -
|| '@'Rexx(Integer.toHexString(hc)).right(8, 0)
return info
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #REALbasic | REALbasic |
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sortable.Shuffle() ' sortable is now randomized
Dim swapped As Boolean
Do
Dim index, bound As Integer
bound = sortable.Ubound
While index < bound
If sortable(index) > sortable(index + 1) Then
Dim s As Integer = sortable(index)
sortable.Remove(index)
sortable.Insert(index + 1, s)
swapped = True
End If
index = index + 1
Wend
Loop Until Not swapped
'sortable is now sorted
|
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Nim | Nim | type Singleton = object # Singleton* would export
foo*: int
var single* = Singleton(foo: 0) |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Objeck | Objeck | class Singleton {
@singleton : static : Singleton;
New : private () {
}
function : GetInstance() ~ Singleton {
if(@singleton <> Nil) {
@singleton := Singleton->New();
};
return @singleton;
}
method : public : DoStuff() ~ Nil {
...
}
} |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #AutoHotkey | AutoHotkey | run, cmd /k
WinWait, ahk_class ConsoleWindowClass
controlsend, ,hello console, ahk_class ConsoleWindowClass |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #AutoHotkey | AutoHotkey | WinActivate, ahk_class MozillaUIWindowClass
Click 200, 200 right ; relative to external window (firefox)
sleep, 2000
WinMinimize
CoordMode, Mouse, Screen
Click 400, 400 right ; relative to top left corner of the screen. |
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #REXX | REXX | /*REXX program sorts an array (of any kind of items) using the bubble─sort algorithm.*/
call gen /*generate the array elements (items).*/
call show 'before sort' /*show the before array elements. */
say copies('▒', 70) /*show a separator line (before/after).*/
call bSort # /*invoke the bubble sort with # items.*/
call show ' after sort' /*show the after array elements. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
bSort: procedure expose @.; parse arg n /*N: is the number of @ array elements.*/
do m=n-1 by -1 until ok; ok=1 /*keep sorting the @ array until done.*/
do j=1 for m; k=j+1; if @.j<[email protected] then iterate /*elements in order? */
[email protected]; @[email protected]; @.k=_; ok=0 /*swap two elements; flag as not done.*/
end /*j*/
end /*m*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
gen: @.=; @.1 = '---letters of the Hebrew alphabet---' ; @.13= "kaph [kaf]"
@.2 = '====================================' ; @.14= "lamed"
@.3 = 'aleph [alef]' ; @.15= "mem"
@.4 = 'beth [bet]' ; @.16= "nun"
@.5 = 'gimel' ; @.17= "samekh"
@.6 = 'daleth [dalet]' ; @.18= "ayin"
@.7 = 'he' ; @.19= "pe"
@.8 = 'waw [vav]' ; @.20= "sadhe [tsadi]"
@.9 = 'zayin' ; @.21= "qoph [qof]"
@.10= 'heth [het]' ; @.22= "resh"
@.11= 'teth [tet]' ; @.23= "shin"
@.12= 'yod' ; @.24= "taw [tav]"
do #=1 until @.#==''; end; #=#-1 /*determine #elements in list; adjust #*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do j=1 for #; say ' element' right(j,length(#)) arg(1)":" @.j; end; return |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Objective-C | Objective-C | // SomeSingleton.h
@interface SomeSingleton : NSObject
{
// any instance variables
}
+ (SomeSingleton *)sharedInstance;
@end |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Oforth | Oforth | Object Class new: Sequence(channel)
Sequence method: initialize(initialValue)
Channel newSize(1) := channel
@channel send(initialValue) drop ;
Sequence method: nextValue @channel receive dup 1 + @channel send drop ; |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #AutoIt | AutoIt | Run("notepad")
WinWaitActive("Untitled - Notepad")
Send("The answer is 42") |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #BASIC | BASIC | 100 REM SIMULATE KEYBORD INPUT
110 GOSUB 170"OPEN&WRITE KB
120 PRINT "HOME:RUN140"M$"MARK
130 PRINT D$C$A$"EXEC"F$: END
140 INPUT "NAME? ";N$
150 PRINT "HELLO, "N$"!"
160 END
170 D$ = CHR$ (4):C$ = "CLOSE"
180 M$ = CHR$ (13):O$ = "OPEN"
190 F$ = "KB":A$ = F$ + M$ + D$
200 PRINT D$"MON I"M$D$O$;
210 PRINT A$C$A$"DELETE"A$O$;
220 PRINT A$"WRITE"F$: RETURN |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #C | C |
#define WINVER 0x500
#include<windows.h>
int main()
{
int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);
int x = maxX/2, y = maxY/2;
double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;
INPUT ip;
ZeroMemory(&ip,sizeof(ip));
ip.type = INPUT_MOUSE;
while(x > 5 || y < maxY-5){
ip.mi.mouseData = 0;
ip.mi.dx = x * factorX;
ip.mi.dy = y * factorY;
ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
SendInput(1,&ip,sizeof(ip));
Sleep(1);
if(x>3)
x-=1;
if(y<maxY-3)
y+=1;
}
ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;
SendInput(1,&ip,sizeof(ip));
return 0;
}
|
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Ring | Ring | bubbleList = [4,2,1,3]
flag = 0
bubbleSort(bubbleList)
see bubbleList
func bubbleSort A
n = len(A)
while flag = 0
flag = 1
for i = 1 to n-1
if A[i] > A[i+1]
temp = A[i]
A[i] = A[i+1]
A[i+1] = temp
flag = 0
ok
next
end
|
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #ooRexx | ooRexx |
a = .singleton~new
b = .singleton~new
a~foo = "Rick"
if a~foo \== b~foo then say "A and B are not the same object"
::class singleton
-- initialization method for the class
::method init class
expose singleton
-- mark this as unallocated. We could also just allocate
-- the singleton now, but better practice is probably wait
-- until it is requested
singleton = .nil
-- override the new method. Since this is a guarded
-- method by default, this is thread safe
::method new class
expose singleton
-- first request? Do the real creation now
if singleton == .nil then do
-- forward to the super class. We use this form of
-- FORWARD rather than explicit call ~new:super because
-- this takes care of any arguments passed to NEW as well.
forward class(super) continue
singleton = result
end
return singleton
-- an attribute that can be used to demonstrate this really is
a singleton.
::attribute foo
|
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #OxygenBasic | OxygenBasic |
Class Singleton
static sys inst 'private
int instantiated() { return inst }
void constructor(){ if not inst then inst=@this }
'all other methods start with @this=inst
end class
'if not singleton.instantiated
new Singleton MySingleton
'endif
|
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #C | C | gcc -o simkeypress -L/usr/X11R6/lib -lX11 simkeypress.c
|
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Clojure | Clojure | (import java.awt.Robot)
(import java.awt.event.KeyEvent)
(defn keytype [str]
(let [robot (new Robot)]
(doseq [ch str]
(if (Character/isUpperCase ch)
(doto robot
(.keyPress (. KeyEvent VK_SHIFT))
(.keyPress (int ch))
(.keyRelease (int ch))
(.keyRelease (. KeyEvent VK_SHIFT)))
(let [upCh (Character/toUpperCase ch)]
(doto robot
(.keyPress (int upCh))
(.keyRelease (int upCh)))))))) |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Common_Lisp | Common Lisp |
(defun sh (cmd)
#+clisp (shell cmd)
#+ecl (si:system cmd)
#+sbcl (sb-ext:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*)
#+clozure (ccl:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*))
(sh "xdotool mousemove 0 0 click 1")
(sleep 2)
(sh "xdotool mousemove 300 300 click 1")
|
|
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Fantom | Fantom |
using fwt
using gfx
class Main
{
public static Void main ()
{
button1 := Button
{
text = "don't click!"
onAction.add |Event e|
{
echo ("clicked by code")
}
}
button2 := Button
{
text = "click"
onAction.add |Event e|
{
// fire all the event listeners on button1
button1.onAction.fire(e)
}
}
Window
{
title = "simulate mouse event"
size = Size (300, 200)
button1,
button2,
}.open
}
}
|
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Ruby | Ruby | class Array
def bubblesort1!
length.times do |j|
for i in 1...(length - j)
if self[i] < self[i - 1]
self[i], self[i - 1] = self[i - 1], self[i]
end
end
end
self
end
def bubblesort2!
each_index do |index|
(length - 1).downto( index ) do |i|
self[i-1], self[i] = self[i], self[i-1] if self[i-1] < self[i]
end
end
self
end
end
ary = [3, 78, 4, 23, 6, 8, 6]
ary.bubblesort1!
p ary
# => [3, 4, 6, 6, 8, 23, 78] |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Oz | Oz | declare
local
class Singleton
meth init
skip
end
end
L = {NewLock}
Instance
in
fun {GetInstance}
lock L then
if {IsFree Instance} then
Instance = {New Singleton init}
end
Instance
end
end
end |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Go | Go | package main
import (
"github.com/micmonay/keybd_event"
"log"
"runtime"
"time"
)
func main() {
kb, err := keybd_event.NewKeyBonding()
if err != nil {
log.Fatal(err)
}
// For linux, need to wait 2 seconds
if runtime.GOOS == "linux" {
time.Sleep(2 * time.Second)
}
//set keys
kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)
//launch
err = kb.Launching()
if err != nil {
log.Fatal(err)
}
} |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #FreeBASIC | FreeBASIC | #include "fbgfx.bi"
#define rect 4
Windowtitle "Mouse events"
Screen 19,32
Dim Shared As Integer xres, yres
Screeninfo xres, yres
Type box
As Single x, y, z
As String caption
As Uinteger textcol, boxcol
End Type
Dim Shared As box label(rect,1)
Dim Shared As box button(rect,1)
Dim Shared As Boolean flag
Dim Shared As fb.event e
Dim As Uinteger background = Rgb(100,100,100)
Sub thickline(x1 As Double, y1 As Double, x2 As Double, y2 As Double,_
thickness As Double, colour As Uinteger, im As Any Pointer = 0)
Dim p As Uinteger = Rgb(255, 255, 254)
If thickness < 2 Then
Line(x1,y1)-(x2,y2), colour
Else
Dim As Double h = Sqr((x2-x1)^2+(y2-y1)^2), s = (y1-y2)/h, c = (x2-x1)/h
For x As Integer = 1 To 2
Line im,(x1+s*thickness/2,y1+c*thickness/2)-(x2+s*thickness/2,y2+c*thickness/2),p
Line im,(x1-s*thickness/2,y1-c*thickness/2)-(x2-s*thickness/2,y2-c*thickness/2),p
Line im,(x1+s*thickness/2,y1+c*thickness/2)-(x1-s*thickness/2,y1-c*thickness/2),p
Line im,(x2+s*thickness/2,y2+c*thickness/2)-(x2-s*thickness/2,y2-c*thickness/2),p
Paint im,((x1+x2)/2, (y1+y2)/2), p, p
p = colour
Next x
End If
End Sub
Function inbox(p1() As box, p2 As box) As Integer
Type pt2d : As Single x, y : End Type
Type ln2d : As pt2d v1, v2 : End Type
#macro isleft(L,p)
-Sgn((L.v1.x-L.v2.x)*(p.y-L.v2.y) - (p.x-L.v2.x)*(L.v1.y-L.v2.y))
#endmacro
Dim As Single n1 = p1(rect,0).z
Dim As Integer index, nextindex
Dim send As ln2d
Dim As Integer n, wn = 0
For n = 1 To 4
index = n Mod 5 : nextindex = (n+1) Mod 5
If nextindex = 0 Then nextindex = 1
send.v1.x = p1(index,n1).x : send.v2.x = p1(nextindex,n1).x
send.v1.y = p1(index,n1).y : send.v2.y = p1(nextindex,n1).y
If p1(index,n1).y <= p2.y Then
If p1(nextindex,n1).y > p2.y Then
If isleft(send,p2) > 0 Then wn += 1
End If
Else
If p1(nextindex,n1).y <= p2.y Then
If isleft(send,p2) < 0 Then wn -= 1
End If
End If
Next n
Return wn
End Function
Sub draw_box(p() As box, col As Uinteger, pnt As String = "paint", im As Any Pointer = 0)
Dim As Integer index, nextindex
Dim As Single n1 = p(rect,0).z
Dim As Double xc, yc
For n As Integer = 1 To 4
xc += p(n,n1).x : yc += p(n,n1).y
index = n Mod 5 : nextindex = (n+1) Mod 5
If nextindex = 0 Then nextindex = 1
thickline(p(index,n1).x,p(index,n1).y, p(nextindex,n1).x,p(nextindex,n1).y,4,col,im)
Next n
xc /= Ubound(p) : yc /= Ubound(p)
If pnt = "paint" Then Paint(xc,yc), col, col
End Sub
Sub highlightbox(box() As box, mp As box, col As Uinteger)
box(rect,0).z = 1
If inbox(box(),mp) Then draw_box(box(),col,"dont_paint")
End Sub
Sub checkbox(box() As box,mp As box)
flag = True
label(rect,1).caption = box(rect,1).caption
label(rect,1).textcol = box(rect,1).textcol
label(rect,1).boxcol = box(rect,1).boxcol
End Sub
Sub drawbox(x As Integer, y As Integer, box()As box, boxlength As Integer, _
boxheight As Integer, col As Uinteger, highlight As Uinteger, caption As String)
Dim As box startpoint
startpoint.x = x : startpoint.y = y
Dim As Integer mmx, mmy
Getmouse mmx, mmy
Dim As box mouse
mouse.x = mmx : mouse.y = mmy
box(rect,1).boxcol = col
box(rect,1).caption = caption
Dim As Uinteger outline, count = 1
outline = Rgb(255,255,255)
For x As Integer = 1 To 4
Select Case x
Case 1
box(1,count).x = startpoint.x
box(1,count).y = startpoint.y
Case 2
box(2,count).x = box(1,count).x + boxlength
box(2,count).y = box(1,count).y
Case 3
box(3,count).x = box(2,count).x
box(3,count).y = box(2,count).y + boxheight
Case 4
box(4,count).x = box(3,count).x - boxlength
box(4,count).y = box(3,count).y
End Select
Next x
box(rect,0).z = 1
draw_box(box(),col)
draw_box(box(),outline,"nopaint")
If inbox(box(),mouse) Then
highlightbox(box(),mouse,highlight)
If (Screenevent(@e)) Then
If e.type = fb.EVENT_MOUSE_BUTTON_PRESS Then checkbox(box(),mouse)
End If
End If
Draw String(box(1,1).x+5,box(1,1).y+5), box(rect,1).caption,box(rect,1).textcol
End Sub
' ---------- Main Program ----------
Do
Screenlock
Cls
Paint(0,0), background
Draw String(300,50), "BUTTON CLICK TEST", Rgb(0,0,200)
drawbox(100,100,button(),100,50,Rgb(200,200,0),Rgb(00,0,200),"Box 1")
drawbox(100,200,button(),100,50,Rgb(200,0,190),Rgb(00,0,200),"Box 2")
drawbox(100,300,button(),100,50,Rgb(0,200,190),Rgb(00,0,200),"Box 3")
If flag Then drawbox(400,100,label(),250,250,label(rect,1).boxcol,Rgb(255,255,255),label(rect,1).caption)
If (Screenevent(@e)) Then
If e.type=13 Then End
End If
Screenunlock
Sleep 1, 1
Loop Until Inkey = Chr(27)
|
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Run_BASIC | Run BASIC | siz = 100
dim data$(siz)
unSorted = 1
WHILE unSorted
unSorted = 0
FOR i = 1 TO siz -1
IF data$(i) > data$(i + 1) THEN
tmp = data$(i)
data$(i) = data$(i + 1)
data$(i + 1) = tmp
unSorted = 1
END IF
NEXT
WEND |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Perl | Perl | package Singleton;
use strict;
use warnings;
my $Instance;
sub new {
my $class = shift;
$Instance ||= bless {}, $class; # initialised once only
}
sub name {
my $self = shift;
$self->{name};
}
sub set_name {
my ($self, $name) = @_;
$self->{name} = $name;
}
package main;
my $s1 = Singleton->new;
$s1->set_name('Bob');
printf "name: %s, ref: %s\n", $s1->name, $s1;
my $s2 = Singleton->new;
printf "name: %s, ref: %s\n", $s2->name, $s2; |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #GUISS | GUISS | Start,Programs,Accessories,Notepad,Textbox,Type:Hello World[pling] |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Java | Java | import java.awt.Robot
public static void type(String str){
Robot robot = new Robot();
for(char ch:str.toCharArray()){
if(Character.isUpperCase(ch)){
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress((int)ch);
robot.keyRelease((int)ch);
robot.keyRelease(KeyEvent.VK_SHIFT);
}else{
char upCh = Character.toUpperCase(ch);
robot.keyPress((int)upCh);
robot.keyRelease((int)upCh);
}
}
} |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Go | Go | package main
import "github.com/go-vgo/robotgo"
func main() {
robotgo.MouseClick("left", false) // single clicks left mouse button
robotgo.MouseClick("right", true) // double clicks right mouse button
} |
|
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #GUISS | GUISS | Start,Programs,Accessories,Notepad,Textbox,Type:Hello World[pling],Menu:File,Save,
Inputbox:filename>greetings.txt,Button:Save |
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Rust | Rust | fn bubble_sort<T: Ord>(values: &mut[T]) {
let mut n = values.len();
let mut swapped = true;
while swapped {
swapped = false;
for i in 1..n {
if values[i - 1] > values[i] {
values.swap(i - 1, i);
swapped = true;
}
}
n = n - 1;
}
}
fn main() {
// Sort numbers.
let mut numbers = [8, 7, 1, 2, 9, 3, 4, 5, 0, 6];
println!("Before: {:?}", numbers);
bubble_sort(&mut numbers);
println!("After: {:?}", numbers);
// Sort strings.
let mut strings = ["empty", "beach", "art", "car", "deal"];
println!("Before: {:?}", strings);
bubble_sort(&mut strings);
println!("After: {:?}", strings);
} |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Phix | Phix | -- <separate include file>
object chk = NULL
class singleton
public procedure check()
if chk==NULL then
chk = this
elsif this!=chk then
?9/0
end if
?"ok"
end procedure
end class
global singleton s = new()
--global singleton s2 = new()
-- </separate include file>
s.check()
--s2.check() -- dies |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #PHP | PHP | class Singleton {
protected static $instance = null;
public $test_var;
private function __construct(){
//Any constructor code
}
public static function getInstance(){
if (is_null(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
}
$foo = Singleton::getInstance();
$foo->test_var = 'One';
$bar = Singleton::getInstance();
echo $bar->test_var; //Prints 'One'
$fail = new Singleton(); //Fatal error |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.Robot
import java.awt.event.KeyEvent
fun sendChars(s: String, pressReturn: Boolean = true) {
val r = Robot()
for (c in s) {
val ci = c.toUpperCase().toInt()
r.keyPress(ci)
r.keyRelease(ci)
}
if (pressReturn) {
r.keyPress(KeyEvent.VK_ENTER)
r.keyRelease(KeyEvent.VK_ENTER)
}
}
fun main(args: Array<String>) {
sendChars("dir") // runs 'dir' command
} |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #LabVIEW | LabVIEW | when defined(windows):
import winlean
else:
{.error: "not supported os".}
type
InputType = enum
itMouse itKeyboard itHardware
KeyEvent = enum
keExtendedKey = 0x0001
keKeyUp = 0x0002
keUnicode = 0x0004
keScanCode = 0x0008
MouseInput {.importc: "MOUSEINPUT".} = object
dx, dy: clong
mouseData, dwFlags, time: culong
dwExtraInfo: int # ULONG_PTR
KeybdInput {.importc: "KEYBDINPUT".} = object
wVk, wScan: cint
dwFlags, time: culong
dwExtraInfo: int
HardwareInput {.importc: "HARDWAREINPUT".} = object
uMsg: clong
wParamL, wParamH: cint
InputUnion {.union.} = object
hi: HardwareInput
mi: MouseInput
ki: KeybdInput
Input = object
`type`: clong
hwin: InputUnion
proc sendInput(total: cint, inp: ptr Input, size: cint) {.importc: "SendInput", header: "<windows.h>".}
proc initKey(keycode: int): Input =
result = Input(`type`: itKeyboard.clong)
var keybd = KeybdInput(wVk: keycode.cint, wScan: 0, time: 0,
dwExtraInfo: 0, dwFlags: 0)
result.hwin = InputUnion(ki: keybd)
proc pressKey(input: var Input) =
input.hwin.ki.dwFlags = keExtendedKey.culong
sendInput(cint 1, addr input, sizeof(Input).cint)
proc releaseKey(input: var Input) =
input.hwin.ki.dwFlags = keExtendedKey.culong or keKeyUp.culong
sendInput(cint 1, addr input, sizeof(Input).cint)
proc pressRelease(input: var Input) =
input.pressKey
input.releaseKey
proc pressReleaseKeycode(input: var Input, code: int) =
input.hwin.ki.wVk = code.cint
input.pressRelease
proc main =
var
shift = initKey 0xa0 # VK_LSHIFT
key = initKey 0x48
pressKey shift
pressRelease key
releaseKey shift
key.pressReleaseKeycode 0x45 # e key
key.pressReleaseKeycode 0x4c # l key
key.pressReleaseKeycode 0x4c # l key
key.pressReleaseKeycode 0x4f # o key
key.pressReleaseKeycode 0x20 # VK_SPACE
key.pressReleaseKeycode 0x57 # w key
key.pressReleaseKeycode 0x4f # o key
key.pressReleaseKeycode 0x52 # r key
key.pressReleaseKeycode 0x4c # l key
key.pressReleaseKeycode 0x44 # d key
main()
|
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Java | Java | Point p = component.getLocation();
Robot robot = new Robot();
robot.mouseMove(p.getX(), p.getY()); //you may want to move a few pixels closer to the center by adding to these values
robot.mousePress(InputEvent.BUTTON1_MASK); //BUTTON1_MASK is the left button,
//BUTTON2_MASK is the middle button, BUTTON3_MASK is the right button
robot.mouseRelease(InputEvent.BUTTON1_MASK); |
|
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Julia | Julia |
# Wrap win32 API function mouse_event() from the User32 dll.
function mouse_event_wrapper(dwFlags,dx,dy,dwData,dwExtraInfo)
ccall((:mouse_event, "User32"),stdcall,Nothing,(UInt32,UInt32,UInt32,UInt32,UInt),dwFlags,dx,dy,dwData,dwExtraInfo)
end
function click()
mouse_event_wrapper(0x2,0,0,0,0)
mouse_event_wrapper(0x4,0,0,0,0)
end
|
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #360_Assembly | 360 Assembly | * Singly-linked list/Element definition 07/02/2017
LISTSINA CSECT
USING LISTSINA,R13 base register
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
* Allocate A
GETMAIN RU,LV=12 get storage
USING NODE,R11 make storage addressable
LR R11,R1 "
MVC VAL,=CL8'A' val='A'
MVC NEXT,=A(0)
DROP R11 base no longer needed
ST R11,A A=@A
* Init LIST
ST R11,LIST init LIST with A
* Allocate C
GETMAIN RU,LV=12 get storage
USING NODE,R11 make storage addressable
LR R11,R1 "
MVC VAL,=CL8'C' val='C'
MVC NEXT,=A(0)
DROP R11 base no longer needed
ST R11,C C=@C
* Insert C After A
MVC P1,A
MVC P2,C
LA R1,PARML
BAL R14,INSERTAF
* Allocate B
GETMAIN RU,LV=12 get storage
USING NODE,R11 make storage addressable
LR R11,R1 "
MVC VAL,=CL8'B' val='B'
MVC NEXT,=A(0)
DROP R11 base no longer needed
ST R11,B B=@B
* Insert B After A
MVC P1,A
MVC P2,B
LA R1,PARML
BAL R14,INSERTAF
* List all
L R11,LIST
USING NODE,R11 address node
LOOP C R11,=A(0)
BE ENDLIST
XPRNT VAL,8
L R11,NEXT
B LOOP
ENDLIST DROP R11
FREEMAIN A=A,LV=12 free A
FREEMAIN A=B,LV=12 free B
FREEMAIN A=C,LV=12 free C
RETURN L R13,4(0,R13) epilog
LM R14,R12,12(R13) " restore
XR R15,R15 " rc=0
BR R14 exit
LIST DS A list head
A DS A
B DS A
C DS A
PARML DS 0A
P1 DS A
P2 DS A
INSERTAF CNOP 0,4
L R2,0(R1) @A
L R3,4(R1) @B
USING NODE,R2 ->A
L R4,NEXT @C
DROP R2
USING NODE,R3 ->B
ST R4,NEXT B.NEXT=@C
DROP R3
USING NODE,R2 ->A
ST R3,NEXT A.NEXT=@B
DROP R2
BR R14 return
LTORG all literals
NODE DSECT node (size=12)
VAL DS CL8
NEXT DS A
YREGS
END LISTSINA |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Sather | Sather | class SORT{T < $IS_LT{T}} is
private swap(inout a, inout b:T) is
temp ::= a;
a := b;
b := temp;
end;
bubble_sort(inout a:ARRAY{T}) is
i:INT;
if a.size < 2 then return; end;
loop
sorted ::= true;
loop i := 0.upto!(a.size - 2);
if a[i+1] < a[i] then
swap(inout a[i+1], inout a[i]);
sorted := false;
end;
end;
until!(sorted);
end;
end;
end; |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #PicoLisp | PicoLisp | (class +Singleton)
(dm message1> ()
(prinl "This is method 1 on " This) )
(dm message2> ()
(prinl "This is method 2 on " This) ) |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #PureBasic | PureBasic | Global SingletonSemaphore=CreateSemaphore(1)
Interface OO_Interface ; Interface for any value of this type
Get.i()
Set(Value.i)
Destroy()
EndInterface
Structure OO_Structure ; The *VTable structure
Get.i
Set.i
Destroy.i
EndStructure
Structure OO_Var
*VirtualTable.OO_Structure
Value.i
EndStructure
Procedure OO_Get(*Self.OO_Var)
ProcedureReturn *Self\Value
EndProcedure
Procedure OO_Set(*Self.OO_Var, n)
*Self\Value = n
EndProcedure
Procedure CreateSingleton()
If TrySemaphore(SingletonSemaphore)
*p.OO_Var = AllocateMemory(SizeOf(OO_Var))
If *p
*p\VirtualTable = ?VTable
EndIf
EndIf
ProcedureReturn *p
EndProcedure
Procedure OO_Destroy(*Self.OO_Var)
FreeMemory(*Self)
SignalSemaphore(SingletonSemaphore)
EndProcedure
DataSection
VTable:
Data.i @OO_Get()
Data.i @OO_Set()
Data.i @OO_Destroy()
EndDataSection |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Nim | Nim | when defined(windows):
import winlean
else:
{.error: "not supported os".}
type
InputType = enum
itMouse itKeyboard itHardware
KeyEvent = enum
keExtendedKey = 0x0001
keKeyUp = 0x0002
keUnicode = 0x0004
keScanCode = 0x0008
MouseInput {.importc: "MOUSEINPUT".} = object
dx, dy: clong
mouseData, dwFlags, time: culong
dwExtraInfo: int # ULONG_PTR
KeybdInput {.importc: "KEYBDINPUT".} = object
wVk, wScan: cint
dwFlags, time: culong
dwExtraInfo: int
HardwareInput {.importc: "HARDWAREINPUT".} = object
uMsg: clong
wParamL, wParamH: cint
InputUnion {.union.} = object
hi: HardwareInput
mi: MouseInput
ki: KeybdInput
Input = object
`type`: clong
hwin: InputUnion
proc sendInput(total: cint, inp: ptr Input, size: cint) {.importc: "SendInput", header: "<windows.h>".}
proc initKey(keycode: int): Input =
result = Input(`type`: itKeyboard.clong)
var keybd = KeybdInput(wVk: keycode.cint, wScan: 0, time: 0,
dwExtraInfo: 0, dwFlags: 0)
result.hwin = InputUnion(ki: keybd)
proc pressKey(input: var Input) =
input.hwin.ki.dwFlags = keExtendedKey.culong
sendInput(cint 1, addr input, sizeof(Input).cint)
proc releaseKey(input: var Input) =
input.hwin.ki.dwFlags = keExtendedKey.culong or keKeyUp.culong
sendInput(cint 1, addr input, sizeof(Input).cint)
proc pressRelease(input: var Input) =
input.pressKey
input.releaseKey
proc pressReleaseKeycode(input: var Input, code: int) =
input.hwin.ki.wVk = code.cint
input.pressRelease
proc main =
var
shift = initKey 0xa0 # VK_LSHIFT
key = initKey 0x48
pressKey shift
pressRelease key
releaseKey shift
key.pressReleaseKeycode 0x45 # e key
key.pressReleaseKeycode 0x4c # l key
key.pressReleaseKeycode 0x4c # l key
key.pressReleaseKeycode 0x4f # o key
key.pressReleaseKeycode 0x20 # VK_SPACE
key.pressReleaseKeycode 0x57 # w key
key.pressReleaseKeycode 0x4f # o key
key.pressReleaseKeycode 0x52 # r key
key.pressReleaseKeycode 0x4c # l key
key.pressReleaseKeycode 0x44 # d key
main()
|
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #OCaml | OCaml | ocaml -I +Xlib Xlib.cma keysym.cma send_event.ml
|
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Kotlin | Kotlin | // version 1.1.2
import java.awt.Robot
import java.awt.event.InputEvent
fun sendClick(buttons: Int) {
val r = Robot()
r.mousePress(buttons)
r.mouseRelease(buttons)
}
fun main(args: Array<String>) {
sendClick(InputEvent.BUTTON3_DOWN_MASK) // simulate a click of the mouse's right button
}
|
|
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Oz | Oz | declare
[QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
Button
Window = {QTk.build td(button(text:"Click me" handle:Button))}
in
{Window show}
{Delay 500}
{Tk.send event(generate Button "<ButtonPress-1>")}
{Delay 500}
{Tk.send event(generate Button "<ButtonRelease-1>")} |
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program defList.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBELEMENTS, 100 // list size
/*******************************************/
/* Structures */
/********************************************/
/* structure linkedlist*/
.struct 0
llist_next: // next element
.struct llist_next + 8
llist_value: // element value
.struct llist_value + 8
llist_fin:
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessInitListe: .asciz "List initialized.\n"
szCarriageReturn: .asciz "\n"
/* datas error display */
szMessErreur: .asciz "Error detected.\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
lList1: .skip llist_fin * NBELEMENTS // list memory place
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrlList1
mov x1,#0
str x1,[x0,#llist_next]
ldr x0,qAdrszMessInitListe
bl affichageMess
100: // standard end of the program
mov x8, #EXIT // request to exit program
svc 0 // perform system call
qAdrszMessInitListe: .quad szMessInitListe
qAdrszMessErreur: .quad szMessErreur
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrlList1: .quad lList1
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #ACL2 | ACL2 | (let ((elem 8)
(next (list 6 7 5 3 0 9)))
(cons elem next)) |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Scala | Scala | def bubbleSort[T](arr: Array[T])(implicit o: Ordering[T]) {
import o._
val consecutiveIndices = (arr.indices, arr.indices drop 1).zipped
var hasChanged = true
do {
hasChanged = false
consecutiveIndices foreach { (i1, i2) =>
if (arr(i1) > arr(i2)) {
hasChanged = true
val tmp = arr(i1)
arr(i1) = arr(i2)
arr(i2) = tmp
}
}
} while(hasChanged)
} |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Python | Python | >>> class Borg(object):
__state = {}
def __init__(self):
self.__dict__ = self.__state
# Any other class names/methods
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>> # For any datum! |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Racket | Racket |
#lang racket
(provide instance)
(define singleton%
(class object%
(super-new)))
(define instance (new singleton%))
|
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Oz | Oz | declare
[QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
Entry
Window = {QTk.build td(entry(handle:Entry))}
in
{Window show}
{Entry getFocus(force:true)}
for C in "Hello, world!" do
Key = if C == 32 then "<space>" else [C] end
in
{Delay 100}
{Tk.send event(generate Entry Key)}
end |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Perl | Perl | $target = "/dev/pts/51";
### How to get the correct value for $TIOCSTI is discussed here : http://www.perlmonks.org/?node_id=10920
$TIOCSTI = 0x5412 ;
open(TTY,">$target") or die "cannot open $target" ;
$b="sleep 99334 &\015";
@c=split("",$b);
sleep(2);
foreach $a ( @c ) { ioctl(TTY,$TIOCSTI,$a); select(undef,undef,undef,0.1);} ;
print "DONE\n"; |
http://rosettacode.org/wiki/Simple_turtle_graphics | Simple turtle graphics | The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.
For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.
See image here: https://i.imgur.com/B7YbTbZ.png
Task
Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as described above. Optionally make it lovely by adding details such as, for example, doors and windows.
Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.
Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed. | #Action.21 | Action! | INCLUDE "D2:TURTLE.ACT" ;from the Action! Tool Kit
PROC Rectangle(INT w,h)
BYTE i
FOR i=1 TO 2
DO
Forward(h)
Left(90)
Forward(w)
Left(90)
OD
RETURN
PROC Square(INT w)
Rectangle(w,w)
RETURN
PROC Triangle(INT w)
BYTE i
FOR i=1 TO 3
DO
Forward(w)
Right(120)
OD
RETURN
PROC House(INT w)
Left(90)
Square(w)
Triangle(w)
Right(90)
RETURN
INT FUNC GetMax(INT ARRAY a INT count)
INT i,max
max=0
FOR i=0 TO count-1
DO
IF a(i)>max THEN
max=a(i)
FI
OD
RETURN (max)
PROC BarChart(INT ARRAY a INT count,w)
INT max,st,i
IF count=0 THEN RETURN FI
max=GetMax(a,count)
st=w/count
Right(90)
FOR i=0 TO count-1
DO
Rectangle(a(i)*w/max,st)
Forward(st)
OD
Left(180)
Forward(w)
RETURN
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
INT ARRAY a=[50 33 200 130 50]
Graphics(8+16)
COLOR1=$0C
COLOR2=$02
Color=1
SetTurtle(150,110,90)
House(75)
Color=0
Right(90)
Forward(5)
Left(90)
Color=1
BarChart(a,5,100)
Right(90)
Forward(5)
Right(90)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Phix | Phix | --
-- demo\rosetta\Simulate_mouse_input.exw
--
-- Note that CURSORPOS, SCREENPOSITION, and MOUSEBUTTON are known to be a little flaky and/or system-dependent, ymmv.
--
without js -- you'd better hope this sort of thing ain't possible in a browser!
requires("1.0.1") -- (IupGetGlobalIntInt)
include pGUI.e
include timedate.e
integer delay = 16 -- (4s @ 250ms)
Ihandle dlg, btn
function action_cb(Ihandle /*btn*/)
string t = format_timedate(date(),"hh:mm:sspm")
IupSetStrAttribute(btn,"TITLE","Clicked at %s",{t})
return IUP_DEFAULT
end function
integer cx, cy
function timer_cb(Ihandle timer)
if delay then
IupSetStrAttribute(btn,"TITLE","%3.2f",{delay/4})
delay -= 1
{cx,cy} = IupGetGlobalIntInt("CURSORPOS")
else
integer {xb,yb} = IupGetIntInt(btn,"SCREENPOSITION"),
{wb,hb} = IupGetIntInt(btn,"RASTERSIZE"),
{dx,dy} = {xb+floor(wb/2),yb+floor(hb/2)}
if {dx,dy}!={cx,cy} then
if IupGetInt(timer,"TIME")=250 then
IupSetInt(timer,"TIME",40)
IupSetInt(timer,"RUN",false)
IupSetInt(timer,"RUN",true)
end if
for i=1 to 15 do
if cx<dx then cx += 1 end if
if cx>dx then cx -= 1 end if
if cy<dy then cy += 1 end if
if cy>dy then cy -= 1 end if
end for
string cxcy = sprintf("%dx%d ",{cx,cy})
IupSetGlobal("CURSORPOS",cxcy)
else
string s = sprintf("%dx%d 1 2",{dx,dy})
IupSetStrGlobal("MOUSEBUTTON", s)
IupSetAttribute(timer,"RUN","NO")
end if
end if
return IUP_CONTINUE
end function
IupOpen()
btn = IupButton("button",Icallback("action_cb"),"SIZE=100x12")
dlg = IupDialog(btn,`TITLE="Simulate mouse input", CHILDOFFSET=10x40, SIZE=200x80`)
IupShow(dlg)
Ihandle timer = IupTimer(Icallback("timer_cb"), 250)
if platform()!=JS then -- (just for consistency)
IupMainLoop()
IupClose()
end if
|
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Action.21 | Action! | DEFINE PTR="CARD"
TYPE ListNode=[
BYTE data
PTR nxt] |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #ActionScript | ActionScript | package
{
public class Node
{
public var data:Object = null;
public var link:Node = null;
public function Node(obj:Object)
{
data = obj;
}
}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Scheme | Scheme | (define (bubble-sort x gt?)
(letrec
((fix (lambda (f i)
(if (equal? i (f i))
i
(fix f (f i)))))
(sort-step (lambda (l)
(if (or (null? l) (null? (cdr l)))
l
(if (gt? (car l) (cadr l))
(cons (cadr l) (sort-step (cons (car l) (cddr l))))
(cons (car l) (sort-step (cdr l))))))))
(fix sort-step x))) |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Raku | Raku | class Singleton {
# We create a lexical variable in the class block that holds our single instance.
my Singleton $instance = Singleton.bless; # You can add initialization arguments here.
method new {!!!} # Singleton.new dies.
method instance { $instance; }
} |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Phix | Phix | --
-- demo\rosetta\Simulate_keyboard_input.exw
--
without js -- you'd better hope this sort of thing ain't possible in a browser!
include pGUI.e
string hw = "Look ma no hands! "
function timer_cb(Ihandle ih)
if length(hw) then
IupSetGlobalInt("KEY",hw[1])
hw = hw[2..$]
else
IupSetInt(ih,"RUN",false)
end if
return IUP_CONTINUE
end function
IupOpen()
Ihandle txt = IupText("SIZE=170x10")
Ihandle dlg = IupDialog(txt,`TITLE="Simulate input", CHILDOFFSET=10x40, SIZE=200x80`)
IupShow(dlg)
Ihandle hTimer = IupTimer(Icallback("timer_cb"), 250)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
http://rosettacode.org/wiki/Simple_turtle_graphics | Simple turtle graphics | The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.
For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.
See image here: https://i.imgur.com/B7YbTbZ.png
Task
Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as described above. Optionally make it lovely by adding details such as, for example, doors and windows.
Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.
Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed. | #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters; use Ada.Characters;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Strings; use Ada.Strings;
-- procedure main - begins program execution
procedure main is
type Sketch_Pad is array(1 .. 50, 1 .. 50) of Character;
thePen : Boolean := True; -- pen raised by default
sketch : Sketch_Pad;
ycorr, xcorr : Integer := 25;
-- specifications
function penPosition(thePen : in out Boolean) return String;
procedure initGrid(sketch : in out Sketch_Pad);
procedure commandMenu(thePen : in out Boolean; xcorr : in out Integer;
ycorr : in out Integer);
procedure showMenu(xcorr : in out Integer; ycorr : in out Integer;
thePen : in out Boolean; sketch : in Sketch_Pad);
procedure moveCursor(thePen : in Boolean; sketch : in out Sketch_Pad;
xcorr : in out Integer; ycorr : in out Integer;
ch : in Integer);
procedure showGrid(sketch : in Sketch_Pad);
-- procedure initGrid - creates the sketchpad and initializes elements
procedure initGrid(sketch : in out Sketch_Pad) is
begin
sketch := (others => (others => ' '));
end initGrid;
-- procedure showMenu - displays the menu for the application
procedure showMenu(xcorr : in out Integer; ycorr : in out Integer;
thePen : in out Boolean; sketch : in Sketch_Pad) is
choice : Integer := 0;
begin
while choice /= 4 loop
Set_Col(15);
Put("TURTLE GRAPHICS APPLICATION");
Set_Col(15);
Put("===========================");
New_Line(2);
Put_Line("Enter 1 to print the grid map");
Put_Line("Enter 2 for command menu");
Put_Line("Enter 3 to raise pen up / down");
Put_Line("Enter 4 to exit the application");
choice := integer'value(Get_Line);
exit when choice = 4;
case choice is
when 1 => showGrid(sketch);
when 2 => commandMenu(thePen, xcorr, ycorr);
when 3 => Put_Line("Pen is "
& penPosition(thePen));
when others => Put_Line("Invalid input");
end case;
end loop;
end showMenu;
-- function penPosition - checks changes the state of whether the pen is
-- raised up or down. If value is True, pen is rasied up
function penPosition(thePen : in out Boolean) return String is
str1 : constant String := "raised UP";
str2 : constant String := "raised DOWN";
begin
if thePen = True then
thePen := False;
return str2;
else
thePen := True;
end if;
return str1;
end penPosition;
-- procedure command menu - provides a list of directions for the turtle
-- to move along the grid
procedure commandMenu(thePen : in out Boolean; xcorr : in out Integer;
ycorr : in out Integer) is
choice : Integer := 0;
begin
while choice <= 0 or choice > 5 loop
Set_Col(15);
Put("Command Menu");
Set_Col(15);
Put("============");
New_Line(2);
Put_Line("To move North enter 1");
Put_Line("To move South enter 2");
Put_Line("To move East enter 3");
Put_Line("To move West enter 4");
Put_Line("To return to previous menu enter 5");
choice := integer'value(Get_Line);
case choice is
when 1 => moveCursor(thePen, sketch, xcorr, ycorr, choice);
when 2 => moveCursor(thePen, sketch, xcorr, ycorr, choice);
when 3 => moveCursor(thePen, sketch, xcorr, ycorr, choice);
when 4 => moveCursor(thePen, sketch, xcorr, ycorr, choice);
when 5 => showMenu(xcorr, ycorr, thePen, sketch);
when others => Put_Line("Invalid choice");
end case;
end loop;
end commandMenu;
-- procedure moveCursor - moves the cursor around the board by taking the
-- x and y coordinates from the user. If the pen is down, a character is
-- printed at that location. If the pen is up, nothing is printed but the
-- cursor still moves to that position
procedure moveCursor(thePen : in Boolean; sketch : in out Sketch_Pad;
xcorr : in out Integer; ycorr : in out Integer;
ch : in Integer) is
begin
if thePen = True then -- pen up so move cursor but do not draw
case ch is
when 1 => xcorr := xcorr - 1; ycorr := ycorr;
sketch(xcorr, ycorr) := ' ';
when 2 => xcorr := xcorr + 1; ycorr := ycorr;
sketch(xcorr, ycorr) := ' ';
when 3 => xcorr := xcorr; ycorr := ycorr + 1;
sketch(xcorr, ycorr) := ' ';
when 4 => xcorr := xcorr; ycorr := ycorr - 1;
sketch(xcorr, ycorr) := ' ';
when others => Put("Unreachable Code");
end case;
else -- pen is down so move cursor and draw
case ch is
when 1 => xcorr := xcorr - 1; ycorr := ycorr;
sketch(xcorr, ycorr) := '#';
when 2 => xcorr := xcorr + 1; ycorr := ycorr;
sketch(xcorr, ycorr) := '#';
when 3 => xcorr := xcorr; ycorr := ycorr + 1;
sketch(xcorr, ycorr) := '#';
when 4 => xcorr := xcorr; ycorr := ycorr - 1;
sketch(xcorr, ycorr) := '#';
when others => Put("Unreachable Code");
end case;
end if;
end moveCursor;
-- procedure showGrid - prints the sketchpad showing the plotted moves
procedure showGrid(sketch : in Sketch_Pad) is
begin
New_Line;
for I in sketch'Range(1) loop
for J in sketch'Range(2) loop
Put(character'image(sketch(I,J)));
end loop;
New_Line;
end loop;
New_Line;
end showGrid;
begin
New_Line;
initGrid(sketch);
showMenu(xcorr, ycorr, thePen, sketch);
New_Line;
end main;
|
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #PicoLisp | PicoLisp | (load "@lib/http.l" "@lib/scrape.l")
# Connect to the demo app at https://7fach.de/app/
(scrape "7fach.de" 80 "app")
# Log in
(expect "'admin' logged in"
(enter 3 "admin") # Enter user name into 3rd field
(enter 4 "admin") # Enter password into 4th field
(press "login") ) # Press the "login" button
(click "Items") # Open "Items" dialog
(click "Spare Part") # Click on "Spare Part" article
(prinl (value 8)) # Print the price (12.50)
(click "logout") # Log out |
|
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #PureBasic | PureBasic | Macro Click()
mouse_event_(#MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
mouse_event_(#MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
EndMacro
; Click at the current location
Click()
Delay(1000) ; Wait a second
; Move to a new location and click it
SetCursorPos_(50, 50)
Click() |
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Ada | Ada | type Link;
type Link_Access is access Link;
type Link is record
Next : Link_Access := null;
Data : Integer;
end record; |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
CO REQUIRES:
MODE OBJVALUE = ~ # Mode/type of actual obj to be stacked #
END CO
MODE OBJNEXTLINK = STRUCT(
REF OBJNEXTLINK next,
OBJVALUE value # ... etc. required #
);
PROC obj nextlink new = REF OBJNEXTLINK:
HEAP OBJNEXTLINK;
PROC obj nextlink free = (REF OBJNEXTLINK free)VOID:
next OF free := obj stack empty # give the garbage collector a BIG hint # |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Scilab | Scilab | function b=BubbleSort(a)
n=length(a)
swapped=%T
while swapped
swapped=%F
for i=1:1:n-1
if a(i)>a(i+1) then
temp=a(i)
a(i)=a(i+1)
a(i+1)=temp
swapped=%T
end
end
end
b=a
endfunction BubbleSort |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Ruby | Ruby | require 'singleton'
class MySingleton
include Singleton
# constructor and/or methods go here
end
a = MySingleton.instance # instance is only created the first time it is requested
b = MySingleton.instance
puts a.equal?(b) # outputs "true" |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Scala | Scala | object Singleton {
// any code here gets executed as if in a constructor
} |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #PicoLisp | PicoLisp | (load "@lib/http.l" "@lib/scrape.l")
# Connect to the demo app at http://7fach.de/8080
(scrape "7fach.de" 80 "8080")
# Log in
(expect "'admin' logged in"
(enter 3 "admin") # Enter user name into 3rd field
(enter 4 "admin") # Enter password into 4th field
(press "login") ) # Press the "login" button
(click "Items") # Open "Items" dialog
(click "Spare Part") # Click on "Spare Part" article
(prinl (value 8)) # Print the price (12.50)
(click "logout") # Log out |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #PowerShell | PowerShell |
Add-Type -AssemblyName Microsoft.VisualBasic
Add-Type -AssemblyName System.Windows.Forms
calc.exe
Start-Sleep -Milliseconds 300
[Microsoft.VisualBasic.Interaction]::AppActivate(“Calc”)
[System.Windows.Forms.SendKeys]::SendWait(“2{ADD}2=”)
|
http://rosettacode.org/wiki/Simple_turtle_graphics | Simple turtle graphics | The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.
For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.
See image here: https://i.imgur.com/B7YbTbZ.png
Task
Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as described above. Optionally make it lovely by adding details such as, for example, doors and windows.
Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.
Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed. | #J | J | ;install each cut 'gl2 gles github:zerowords/tgsjo' |
http://rosettacode.org/wiki/Simple_turtle_graphics | Simple turtle graphics | The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.
For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.
See image here: https://i.imgur.com/B7YbTbZ.png
Task
Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as described above. Optionally make it lovely by adding details such as, for example, doors and windows.
Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.
Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed. | #Julia | Julia | using Luxor, Colors
function house(🐢, x, y, siz)
oldorientation = 🐢.orientation
xpos, ypos = 🐢.xpos, 🐢.ypos
# house wall
Reposition(🐢, x, y)
Rectangle(🐢, siz, siz)
# roof
Reposition(🐢, x - siz / 2, y - siz / 2)
Turn(🐢, -60)
Forward(🐢, siz)
Turn(🐢, 120)
Forward(🐢, siz)
# turtle_demo
doorheight, doorwidth = siz / 2, siz / 4
Pencolor(🐢, 0, 0, 0)
Reposition(🐢, x, y + doorheight / 2)
Rectangle(🐢, doorwidth, doorheight)
# window
windowheight, windowwidth = siz /3, siz / 4
Reposition(🐢, x + siz / 4, y - siz / 4)
Rectangle(🐢, windowwidth, windowheight)
Reposition(🐢, x - siz / 4, y - siz / 4)
Rectangle(🐢, windowwidth, windowheight)
Orientation(🐢, oldorientation)
Reposition(🐢, xpos, ypos)
end
function barchart(🐢, data, x, y, siz)
oldorientation = 🐢.orientation
xpos, ypos = 🐢.xpos, 🐢.ypos
maxdata = maximum(data)
# scale to fit within a square with sides `siz` and draw bars of chart
barwidth = siz / length(data)
Pencolor(🐢, 1.0, 0.0, 0.5)
Reposition(🐢, x, y)
for n in data # draw each bar in chart
barheight = n * siz / maxdata
Reposition(🐢, x, y - barheight / 2)
Rectangle(🐢, barwidth, barheight)
x += barwidth
end
Orientation(🐢, oldorientation)
Reposition(🐢, xpos, ypos)
end
function testturtle(width = 400, height = 600)
dra = Drawing(600, 400, "turtle_demo.png")
origin()
background("midnightblue")
🐢 = Turtle()
Pencolor(🐢, "cyan")
Penwidth(🐢, 1.5)
house(🐢, -width / 3, height / 7, width / 2)
barchart(🐢, [15, 10, 50, 35, 20], width / 8, height / 8, width / 2)
finish()
end
testturtle()
|
http://rosettacode.org/wiki/Simple_turtle_graphics | Simple turtle graphics | The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.
For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.
See image here: https://i.imgur.com/B7YbTbZ.png
Task
Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as described above. Optionally make it lovely by adding details such as, for example, doors and windows.
Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.
Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed. | #Logo | Logo | to rectangle :width :height
repeat 2 [
forward :height
left 90
forward :width
left 90 ]
end
to square :size
rectangle size size
end
to triangle :size
repeat 3 [
forward size
right 120 ]
end
to house :size
left 90
square size
triangle size
right 90
end
to max :lst
if equalp count lst 1 [ output first lst ]
make "x max butfirst lst
if x > first lst [ output x ]
output first lst
end
to barchart :lst :size
right 90
if emptyp lst [ stop ]
make "scale size / (max lst)
make "width size / count lst
foreach lst [
rectangle ? * scale width
forward width ]
back size
left 90
end
clearscreen hideturtle
house 150
penup
right 90 forward 10 left 90
pendown
barchart [ 0.5 0.33333 2 1.3 0.5 ] 200
left 90 back 10 right 90 |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Python | Python | import ctypes
def click():
ctypes.windll.user32.mouse_event(0x2, 0,0,0,0) # Mouse LClick Down, relative coords, dx=0, dy=0
ctypes.windll.user32.mouse_event(0x4, 0,0,0,0) # Mouse LClick Up, relative coords, dx=0, dy=0
click() |
|
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Racket | Racket |
#lang at-exp racket
(require ffi/unsafe)
(define mouse-event
(get-ffi-obj "mouse_event" (ffi-lib "user32")
(_fun _int32 _int32 _int32 _int32 _pointer -> _void)))
(mouse-event #x2 0 0 0 #f)
(mouse-event #x4 0 0 0 #f)
|
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #ALGOL_W | ALGOL W | % record type to hold a singly linked list of integers %
record ListI ( integer iValue; reference(ListI) next );
% declare a variable to hold a list %
reference(ListI) head;
% create a list of integers %
head := ListI( 1701, ListI( 9000, ListI( 42, ListI( 90210, null ) ) ) ); |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program defList.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3
.equ WRITE, 4
.equ NBELEMENTS, 100 @ list size
/*******************************************/
/* Structures */
/********************************************/
/* structure linkedlist*/
.struct 0
llist_next: @ next element
.struct llist_next + 4
llist_value: @ element value
.struct llist_value + 4
llist_fin:
/* Initialized data */
.data
szMessInitListe: .asciz "List initialized.\n"
szCarriageReturn: .asciz "\n"
/* datas error display */
szMessErreur: .asciz "Error detected.\n"
/* UnInitialized data */
.bss
lList1: .skip llist_fin * NBELEMENTS @ list memory place
/* code section */
.text
.global main
main:
ldr r0,iAdrlList1
mov r1,#0
str r1,[r0,#llist_next]
ldr r0,iAdrszMessInitListe
bl affichageMess
100: @ standard end of the program
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessInitListe: .int szMessInitListe
iAdrszMessErreur: .int szMessErreur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrlList1: .int lList1
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
|
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program afficheList64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBELEMENTS, 100 // list size
/*******************************************/
/* Structures */
/********************************************/
/* structure linkedlist*/
.struct 0
llist_next: // next element
.struct llist_next + 8
llist_value: // element value
.struct llist_value + 8
llist_fin:
/* Initialized data */
.data
szMessInitListe: .asciz "List initialized.\n"
szCarriageReturn: .asciz "\n"
/* datas error display */
szMessErreur: .asciz "Error detected.\n"
/* datas message display */
szMessResult: .asciz "Element No : @ value @ \n"
/* UnInitialized data */
.bss
lList1: .skip llist_fin * NBELEMENTS // list memory place
sZoneConv: .skip 100
/* code section */
.text
.global main
main:
ldr x0,qAdrlList1
mov x1,#0 // list init
str x1,[x0,#llist_next]
ldr x0,qAdrszMessInitListe
bl affichageMess
ldr x0,qAdrlList1
mov x1,#2
bl insertElement // add element value 2
ldr x0,qAdrlList1
mov x1,#5
bl insertElement // add element value 5
// // display elements of list
ldr x3,qAdrlList1
mov x2,#0 // ident element
1:
ldr x0,[x3,#llist_next] // end list ?
cmp x0,#0
beq 100f // yes
add x2,x2,#1
mov x0,x2 // display No element and value
ldr x1,qAdrsZoneConv
bl conversion10S
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc
mov x5,x0 // address of new string
ldr x0,[x3,#llist_value]
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5 // new address of message
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc
bl affichageMess
ldr x3,[x3,#llist_next] // next element
b 1b // and loop
100: // standard end of the program
mov x8, #EXIT // request to exit program
svc 0 // perform system call
qAdrszMessInitListe: .quad szMessInitListe
qAdrszMessErreur: .quad szMessErreur
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrlList1: .quad lList1
qAdrszMessResult: .quad szMessResult
qAdrsZoneConv: .quad sZoneConv
/******************************************************************/
/* insert element at end of list */
/******************************************************************/
/* x0 contains the address of the list */
/* x1 contains the value of element */
/* x0 returns address of element or - 1 if error */
insertElement:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,#llist_fin * NBELEMENTS
add x2,x2,x0 // compute address end list
1: // start loop
ldr x3,[x0,#llist_next] // load next pointer
cmp x3,#0 // = zero
csel x0,x3,x0,ne
bne 1b // no -> loop with pointer
add x3,x0,#llist_fin // yes -> compute next free address
cmp x3,x2 // > list end
bge 99f // yes -> error
str x3,[x0,#llist_next] // store next address in current pointer
str x1,[x0,#llist_value] // store element value
mov x1,#0
str x1,[x3,#llist_next] // init next pointer in next address
b 100f
99: // error
mov x0,-1
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Scratch | Scratch | const proc: bubbleSort (inout array elemType: arr) is func
local
var boolean: swapped is FALSE;
var integer: i is 0;
var elemType: help is elemType.value;
begin
repeat
swapped := FALSE;
for i range 1 to length(arr) - 1 do
if arr[i] > arr[i + 1] then
help := arr[i];
arr[i] := arr[i + 1];
arr[i + 1] := help;
swapped := TRUE;
end if;
end for;
until not swapped;
end func; |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Sidef | Sidef | class Singleton(name) {
static instance;
method new(name) {
instance := Singleton.bless(Hash(:name => name));
}
method new {
Singleton.new(nil);
}
}
var s1 = Singleton('foo');
say s1.name; #=> 'foo'
say s1.object_id; #=> '30424504'
var s2 = Singleton();
say s2.name; #=> 'foo'
say s2.object_id; #=> '30424504'
s2.name = 'bar'; # change name in s2
say s1.name; #=> 'bar' |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #PureBasic | PureBasic | If AW_WinActivate("Calc")
AW_SendKeys("123+3=")
EndIf |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Python | Python | import autopy
autopy.key.type_string("Hello, world!") # Prints out "Hello, world!" as quickly as OS will allow.
autopy.key.type_string("Hello, world!", wpm=60) # Prints out "Hello, world!" at 60 WPM.
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW) |
http://rosettacode.org/wiki/Simple_turtle_graphics | Simple turtle graphics | The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.
For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.
See image here: https://i.imgur.com/B7YbTbZ.png
Task
Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as described above. Optionally make it lovely by adding details such as, for example, doors and windows.
Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.
Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed. | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Simple_turtle_graphics
use warnings;
use Tk;
use List::Util qw( max );
my $c; # the canvas
# turtle routines
my $pen = 1; # true for pendown, false for penup
my @location = (0, 0); # upper left corner
my $direction = 0; # 0 for East, increasing clockwise
my @stack;
my $radian = 180 / atan2 0, -1;
sub dsin { sin $_[0] / $radian }
sub dcos { cos $_[0] / $radian }
sub save { push @stack, [ $direction, @location ] }
sub restore { ($direction, @location) = @{ pop @stack } }
sub turn { $direction += shift }
sub right { turn shift }
sub left { turn -shift }
sub forward
{
my $x = $location[0] + $_[0] * dcos $direction;
my $y = $location[1] + $_[0] * dsin $direction;
$pen and $c->createLine( @location, $x, $y, -width => 3 );
@location = ($x, $y);
}
sub back { turn 180; forward shift; turn 180 }
sub penup { $pen = 0 }
sub pendown { $pen = 1 }
sub text { $c->createText( @location, -text => shift ) }
# make window
my $mw = MainWindow->new;
$c = $mw->Canvas(
-width => 900, -height => 900,
)->pack;
$mw->Button(-text => 'Exit', -command => sub {$mw->destroy},
)->pack(-fill => 'x');
$mw->after(0, \&run);
MainLoop;
-M $0 < 0 and exec $0;
sub box
{
my ($w, $h) = @_;
for (1 .. 2)
{
forward $w;
left 90;
forward $h;
left 90;
}
}
sub house
{
my $size = shift;
box $size, $size;
right 90;
for ( 1 .. 3 )
{
right 120;
forward $size;
}
penup;
left 90;
forward $size;
left 90;
save;
forward $size * 1 / 4;
pendown;
box $size / 4, $size / 2;
penup;
forward $size * 3 / 8;
left 90;
forward $size / 4;
right 90;
pendown;
box $size / 4, $size / 4;
penup;
restore;
save;
forward $size / 2;
left 90;
forward $size + 40;
right 90;
pendown;
for (1 .. 8)
{
forward 15;
left 45;
forward 15;
}
restore;
penup;
}
sub graph
{
save;
my $size = shift;
my $width = $size / @_;
my $hscale = $size / max @_;
for ( @_ )
{
box $width, $hscale * $_;
save;
penup;
forward $width / 2;
left 90;
forward 10;
text $_;
pendown;
restore;
forward $width;
}
restore;
}
sub run
{
penup;
forward 50;
right 90;
forward 400;
pendown;
house(300);
penup;
forward 400;
pendown;
graph( 400, 2,7,4,5,1,8,6 );
} |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Raku | Raku | use X11::libxdo;
my $xdo = Xdo.new;
my ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );
sleep .25;
for ^$dw -> $mx {
my $my = (($mx / $dh * τ).sin * 500).abs.Int + 200;
$xdo.move-mouse( $mx, $my, 0 );
my ($x, $y, $window-id, $screen) = $xdo.get-mouse-info;
my $name = (try $xdo.get-window-name($window-id) if $window-id)
// 'No name set';
my $line = "Mouse location: x=$x : y=$y\nWindow under mouse:\nWindow ID: " ~
$window-id ~ "\nWindow name: " ~ $name ~ "\nScreen #: $screen";
print "\e[H\e[J", $line;
sleep .001;
}
say '';
#`[ There are several available routines controlling mouse position and button events.
.move-mouse( $x, $y, $screen ) # Move the mouse to a specific location.
.move-mouse-relative( $delta-x, $delta-y ) # Move the mouse relative to it's current position.
.move-mouse-relative-to-window( $x, $y, $window ) # Move the mouse to a specific location relative to the top-left corner of a window.
.get-mouse-location() # Get the current mouse location (coordinates and screen ID number).
.get-mouse-info() # Get all mouse location-related data.
.wait-for-mouse-to-move-from( $origin-x, $origin-y ) # Wait for the mouse to move from a location.
.wait-for-mouse-to-move-to( $dest-x, $dest-y ) # Wait for the mouse to move to a location.
.mouse-button-down( $window, $button ) # Send a mouse press (aka mouse down) for a given button at the current mouse location.
.mouse-button-up( $window, $button ) # Send a mouse release (aka mouse up) for a given button at the current mouse location.
.mouse-button-click( $window, $button ) # Send a click for a specific mouse button at the current mouse location.
.mouse-button-multiple( $window, $button, $repeat = 2, $delay? ) # Send a one or more clicks of a specific mouse button at the current mouse location.
]
|
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #ATS | ATS | (* The Rosetta Code linear list type can contain any vt@ype.
(The ‘@’ means it doesn’t have to be the size of a pointer.
You can read {0 <= n} as ‘for all non-negative n’. *)
dataviewtype rclist_vt (vt : vt@ype+, n : int) =
| rclist_vt_nil (vt, 0)
| {0 <= n} rclist_vt_cons (vt, n + 1) of (vt, rclist_vt (vt, n))
(* A lemma one will need: lists never have negative lengths. *)
extern prfun {vt : vt@ype}
lemma_rclist_vt_param
{n : int}
(lst : !rclist_vt (vt, n)) :<prf> [0 <= n] void
(* Proof of the lemma. *)
primplement {vt}
lemma_rclist_vt_param lst =
case+ lst of
| rclist_vt_nil () => ()
| rclist_vt_cons _ => () |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #AutoHotkey | AutoHotkey | element = 5 ; data
element_next = element2 ; link to next element |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ACL2 | ACL2 | (defun traverse (xs)
(if (endp xs)
(cw "End.~%")
(prog2$ (cw "~x0~%" (first xs))
(traverse (rest xs))))) |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Action.21 | Action! | SET EndProg=* |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #11l | 11l | V seconds = Float(input())
print(‘Sleeping...’)
sleep(seconds)
print(‘Awake!’) |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Seed7 | Seed7 | const proc: bubbleSort (inout array elemType: arr) is func
local
var boolean: swapped is FALSE;
var integer: i is 0;
var elemType: help is elemType.value;
begin
repeat
swapped := FALSE;
for i range 1 to length(arr) - 1 do
if arr[i] > arr[i + 1] then
help := arr[i];
arr[i] := arr[i + 1];
arr[i + 1] := help;
swapped := TRUE;
end if;
end for;
until not swapped;
end func; |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Slate | Slate | define: #Singleton &builder: [Oddball clone] |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Racket | Racket | #lang racket/gui
(define frame (new frame%
(label "Example")
(width 300)
(height 300))) ; Defines an instance of a frame to put the canvas in
(define simulate-key-canvas%
(class canvas%
(define/public (simulate-key key)
(send this on-char key)) ; Creates a class that inherits from the standard canvas class, that can receive simulated key presses
(define/override (on-char key)
(displayln (send key get-key-code))) ; Changes the method that receives key presses to show some output
(super-new)))
(define canvas
(new simulate-key-canvas%
(parent frame))) ; Defines an instance of the newly created class
(send frame show #t) ; Shows the frame with a white canvas inside
(send canvas simulate-key (new key-event% (key-code #\k))) ; Sends the simulated key press (with a key-event% instance)
;outputs k |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #Raku | Raku | use X11::libxdo;
my $xdo = Xdo.new;
my $active = $xdo.get-active-window;
my $command = $*VM.config<os> eq 'darwin' ?? 'open' !! 'xdg-open';
shell "$command https://www.google.com";
sleep 1;
my $match = rx[^'Google '];
say my $w = $xdo.search(:name($match))<ID>;
sleep .25;
if $w {
$xdo.activate-window($w);
say "Window name: ", $xdo.get-window-name( $w );
$xdo.type($w, 'Raku language');
sleep .25;
$xdo.send-sequence($w, 'Tab');
sleep .5;
$xdo.send-sequence($w, 'Tab');
sleep .5;
$xdo.send-sequence($w, 'Tab');
sleep .5;
$xdo.send-sequence($w, 'Return');
} |
http://rosettacode.org/wiki/Simple_turtle_graphics | Simple turtle graphics | The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.
For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.
See image here: https://i.imgur.com/B7YbTbZ.png
Task
Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as described above. Optionally make it lovely by adding details such as, for example, doors and windows.
Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.
Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed. | #Phix | Phix | -- demo\rosetta\turtle.e
include pGUI.e
global Ihandle canvas, dlg
global cdCanvas cdcanvas
global bool pen_down = false
global procedure pendown(atom colour=CD_BLACK)
pen_down = true
cdCanvasSetForeground(cdcanvas, colour)
end procedure
global procedure penup()
pen_down = false
end procedure
|
http://rosettacode.org/wiki/Simple_turtle_graphics | Simple turtle graphics | The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.
For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.
See image here: https://i.imgur.com/B7YbTbZ.png
Task
Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as described above. Optionally make it lovely by adding details such as, for example, doors and windows.
Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.
Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed. | #Python | Python | from turtle import *
def rectangle(width, height):
for _ in range(2):
forward(height)
left(90)
forward(width)
left(90)
def square(size):
rectangle(size, size)
def triangle(size):
for _ in range(3):
forward(size)
right(120)
def house(size):
right(180)
square(size)
triangle(size)
right(180)
def barchart(lst, size):
scale = size/max(lst)
width = size/len(lst)
for i in lst:
rectangle(i*scale, width)
penup()
forward(width)
pendown()
penup()
back(size)
pendown()
clearscreen()
hideturtle()
house(150)
penup()
forward(10)
pendown()
barchart([0.5, (1/3), 2, 1.3, 0.5], 200)
penup()
back(10)
pendown() |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Ring | Ring |
# Project : Simulate input/Mouse
load "guilib.ring"
load "stdlib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("")
setgeometry(100,100,800,600)
setwindowtitle("Mouse events")
line1 = new qlineedit(win1) {
setgeometry(150,450,300,30)
settext("")}
line2 = new qlineedit(win1) {
setgeometry(150,400,300,30)
settext("")}
new qpushbutton(win1) {
setgeometry(150,500,300,30)
settext("draw")
myfilter = new qallevents(win1)
myfilter.setMouseButtonPressevent("drawpress()")
myfilter.setMouseButtonReleaseevent("drawrelease()")
installeventfilter(myfilter)
}
show()
}
exec()
}
func drawpress()
line2.settext("")
line1.settext("Mouse was pressed")
func drawrelease()
line1.settext("")
line2.settext("Mouse was released")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.