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/Simulate_input/Mouse | Simulate input/Mouse | #Rust | Rust | extern crate autopilot;
extern crate rand;
use rand::Rng;
// Moves the mouse in a sine wave across the screen.
const TWO_PI: f64 = std::f64::consts::PI * 2.0;
fn sine_mouse_wave() -> Result<(), autopilot::mouse::MouseError> {
let screen_size = autopilot::screen::size();
let scoped_height = screen_size.height / 2.0 - 10.0; // Stay in screen bounds.
for x in 0..screen_size.width as u64 {
let y = (scoped_height * ((TWO_PI * x as f64) / screen_size.width).sin() + scoped_height)
.round();
let duration: u64 = rand::thread_rng().gen_range(1, 3);
try!(autopilot::mouse::move_to(autopilot::geometry::Point::new(
x as f64,
y as f64
)));
std::thread::sleep(std::time::Duration::from_millis(duration));
}
Ok(())
}
fn main() {
sine_mouse_wave().expect("Unable to move mouse");
} |
|
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 | #AWK | AWK |
BEGIN {
NIL = 0
HEAD = 1
LINK = 1
VALUE = 2
delete list
initList()
}
function initList() {
delete list
list[HEAD] = makeNode(NIL, NIL)
}
function makeNode(link, value) {
return link SUBSEP value
}
function getNode(part, nodePtr, linkAndValue) {
split(list[nodePtr], linkAndValue, SUBSEP)
return linkAndValue[part]
}
|
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 | #Axe | Axe | Lbl LINK
r₂→{r₁}ʳ
0→{r₁+2}ʳ
r₁
Return
Lbl NEXT
{r₁+2}ʳ
Return
Lbl VALUE
{r₁}ʳ
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
| #ActionScript | ActionScript | var A:Node;
//...
for(var i:Node = A; i != null; i = i.link)
{
doStuff(i);
} |
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
| #Ada | Ada | with Ada.Containers.Doubly_Linked_Lists;
with Ada.Text_Io; use Ada.Text_Io;
procedure Traversal_Example is
package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer);
use Int_List;
procedure Print(Position : Cursor) is
begin
Put_Line(Integer'Image(Element(Position)));
end Print;
The_List : List;
begin
for I in 1..10 loop
The_List.Append(I);
end loop;
-- Traverse the list, calling Print for each value
The_List.Iterate(Print'access);
end traversal_example; |
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
| #360_Assembly | 360 Assembly |
START
PRINT DATA,GEN
YREGS , REGISTER EQUATES (e.g. 0 = R0)
SLEEP CSECT
SLEEP AMODE 31 addressing mode 31 bit
SLEEP RMODE ANY loader determines 31 or 24
***********************************************************************
* REENTRANT. Logically swap out a task for a number of seconds
* specified in PARM. Minimum 0, maximum 60 seconds
*
* MVS rexx (the original rexx) does not have a sleep function. This
* program can be called from rexx, assuming this program is in
* LINKLIST, as follows:
*
* /* rexx */
* wait_time = '6' /* number of seconds to sleep */
* say 'Sleeping...'
* address LINKMVS "SLEEP wait_time" /* invoke SLEEP */
* say 'Awake!
***********************************************************************
PROLOG BAKR R14,0 satck caller's registers
LR R4,R1 save parm pointer
LR R12,R15 entry point addr to R12
USING SLEEP,R12 tell assembler about that
B AROUND avoid abend S0C1
DC C'SLEEP ' CSECT NAME
DC C'C=2014.05.10 ' CHANGE DATE
DC C'A=&SYSDATE ' ASSEMBLY DATE
DC C'T=&SYSTIME ' CHANGE TIME
DC C'MarcvdM. ' PROGRAMMER NAME
AROUND L R10,0(0,R4) load parm address in R10
XR R15,R15 clear R15
LH R15,0(0,R10) load parm length in R15
LR R6,R15 save length in R6
LTR R15,R15 parm length 0?
BZ NOPARM yes, exit before getmain
C R6,F2 parmlength > 2 ?
BH NOPARM yes, exit before getmain
STORAGE OBTAIN,LENGTH=WALEN,LOC=ANY get some storage
LR R9,R1 address of storage in R9
USING WAREAX,R9 base for data section (DSECT)
MVC EYECAT,=C'**MARC**' make storage easy to find in dump
MVC SECONDS,C00 set field to F0F0
C R6,F1 parmlength = 1?
BNE COPYSECS no, copy both bytes
MVC SECONDS+1(1),2(R10) yes, just copy one byte.
B TRTEST
COPYSECS MVC SECONDS,2(R10)
* test supplied parameter for valid integer values
TRTEST TRT SECONDS(1),VALINT6 first parm byte no higher as 6?
BNZ NOPARM_REL higher, release storage and return
TRT SECONDS+1(1),VALINT9 second byte valid?
BNZ NOPARM_REL no, release storage and return
CLC SECONDS(1),=C'6' first parm byte < 6?
BNE DOWAIT yes, do wait
CLC SECONDS+1(1),=C'0' first eq. 6, second > 0?
BNE NOPARM_REL yes, release storage and return
DOWAIT DS 0H
MVC WAWTO(DWTOL),DWTO copy WTO list form to obtained st.
MVC WAWTO+18(2),SECONDS copy in nr. of seconds
WTO MF=(E,WAWTO) issue WTO, execute form
MVC HOURS,C00 zero out hours
MVC MINUTS,C00 and minutes
MVC REST,C00 and milliseconds
STIMER WAIT,DINTVL=TIMEVAL SVC 47: logical swap out (sleep)
B EXIT done
NOPARM_REL DS 0H
STORAGE RELEASE,ADDR=(R9),LENGTH=WALEN free obtained storage
LA R15,4 set return code 4
B RETURN return to caller
EXIT DS 0H
STORAGE RELEASE,ADDR=(R9),LENGTH=WALEN free obtained storage
WTO ' Awake!',ROUTCDE=11 fixed wake-up string
NOPARM EQU *
RETURN PR , return to caller
*
* --------------------------------------------------------------------
* CONSTANTS
* --------------------------------------------------------------------
DWTO WTO ' Sleeping... (XX seconds)',ROUTCDE=11,MF=L
DWTOL EQU *-DWTO length of WTO list form
F1 DC F'1'
F2 DC F'2'
C00 DC C'00'
VALINT6 DC 256XL1'01'
ORG *-16
VALOK6 DC 7XL1'00' F0-F6: OFFSETS 240-246
VALINT9 DC 256XL1'01'
ORG *-16
VALOK9 DC 10XL1'00' F0-F9: OFFSETS 240-249
DS 0D
LTORG , FORCE DISPLACEMENT LITERALS
* --------------------------------------------------------------------
* DSECT (data section)
* --------------------------------------------------------------------
WAREAX DSECT ,
WAWTO DS CL(DWTOL) reentrant WTO area
EYECAT DS CL8
TIMEVAL DS 0CL8
HOURS DS CL2 will be zeroed
MINUTS DS CL2 will be zeroed
SECONDS DS CL2 from parm
REST DS CL2 will be zeroed
WALEN EQU *-WAREAX length of DSECT
* --------------------------------------------------------------------
END SLEEP
|
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
| #8051_Assembly | 8051 Assembly | ORG RESET
jmp main
ORG TIMER0
; timer interrupt only used to wake the processor
clr tr0
reti
main:
setb ea ; enable interrupts
setb et0 ; enable timer0 interrupt
mov tl0, #0 ; start timer counter at zero
mov th0, #0 ; these two values dictate the length of sleep
mov a, pcon ; copy power control register
setb a.0 ; set idl bit
setb tr0 ; start timer
; sleeping...
mov pcon, a ; move a back into pcon (processor sleeps after this instruction finishes)
; when the timer overflows and the timer interrupt returns, execution will resume at this spot
; Awake!
jmp $ |
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.
| #Shen | Shen | (tc +)
(define swap
{ (vector number) --> number --> number --> (vector number) }
A I1 I2 -> (let Z (<-vector A I1)
(do (vector-> A I1 (<-vector A I2))
(vector-> A I2 Z))))
(define one-pass
{ (vector number) --> number --> boolean --> number --> boolean }
A N Swapped N -> (do (if (> (<-vector A (- N 1)) (<-vector A N))
(swap A (- N 1) N))
Swapped)
A N Swapped I -> (if (> (<-vector A (- I 1)) (<-vector A I))
(do (swap A (- I 1) I)
(one-pass A N true (+ I 1)))
(one-pass A N Swapped (+ I 1))))
(define bubble-h
{ boolean --> (vector number) --> number --> (vector number) }
true A N -> (bubble-h (one-pass A N false 2) A N)
false A N -> A)
(define bubble-sort
{ (vector number) --> (vector number) }
A -> (let N (limit A)
(bubble-h (one-pass A N false 2) A N))) |
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.
| #Smalltalk | Smalltalk |
SomeClass class>>sharedInstance
SharedInstance ifNil: [SharedInstance := self basicNew initialize].
^ SharedInstance
|
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.
| #Swift | Swift |
class SingletonClass {
static let sharedInstance = SingletonClass()
///Override the init method and make it private
private override init(){
// User can do additional manipulations here.
}
}
// Usage
let sharedObject = SingletonClass.sharedInstance
|
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).
| #REXX | REXX | /*REXX pgm shows how to use the REXX/PC PRESS cmd to simulate keyboard input.*/
call press 'This text will be put into a buffer as if it came from the keyboard'
/* [↑] text will be available for any program to use (including DOS).*/
/*stick a fork in it, we're all done. */ |
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).
| #Rust | Rust | extern crate autopilot;
fn main() {
autopilot::key::type_string("Hello, world!", None, None, &[]);
} |
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. | #Quackery | Quackery | [ $ "turtleduck.qky" loadfile ] now!
[ behead do
rot witheach
[ do 2over 2over
v< if 2swap
2drop ] ] is largest ( [ --> n/d )
[ 2 times
[ 2dup walk
-1 4 turn
2over walk
-1 4 turn ]
2drop 2drop ] is rectangle ( n/d n/d --> )
[ 2dup rectangle ] is square ( n/d --> )
[ 3 times
[ 2dup walk
1 3 turn ]
2drop ] is triangle ( n/d --> )
[ 1 2 turn
2dup square triangle
1 2 turn ] is house ( n/d --> )
[ stack ] is bar.width ( --> s )
[ stack ] is bar.scale ( --> s )
[ join temp put
dup size n->v
temp share do v/ 1/v
join bar.width put
dup largest
temp share do v/
join bar.scale put
witheach
[ do
bar.scale share do v/
bar.width share do
rectangle
bar.width share do fly ]
temp take do -v fly
bar.width release
bar.scale release ] is barchart ( [ n/d --> )
turtle
150 1 house
10 1 fly
' [ [ 1 2 ] [ 1 3 ] [ 2 1 ] [ 13 10 ] [ 1 2 ] ] 200 1 barchart
-10 1 fly |
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. | #Wren | Wren | import "dome" for Window
import "graphics" for Canvas, Color
import "./turtle" for Turtle
class Main {
construct new(width, height) {
Window.resize(width, height)
Canvas.resize(width, height)
Window.title = "Simple turtle graphics"
_w = width
_h = height
}
init() {
Canvas.cls(Color.white)
_t = Turtle.new()
drawHouse(_w/4)
barChart([15, 10, 50, 35, 20], _w/3)
}
drawHouse(size) {
// save initial turtle position and direction
var saveX = _t.x
var saveY = _t.y
var saveD = _t.dir
_t.pen.width = 2
// draw house
_t.drawRect(_w/4, _h/2, size, size)
// draw roof
_t.right(30)
_t.walk(size)
_t.right(120)
_t.walk(size)
// draw door
var doorWidth = (size/4).floor
var doorHeight = (size/2).floor
_t.drawRect(_w/4 + doorWidth/2, _h/2 + doorHeight, doorWidth, doorHeight)
// draw window
var windWidth = (size/3).floor
var windHeight = (size/4).floor
_t.drawRect(_w/4 + size/2, _h/2 + size/2, windWidth, windHeight)
// restore initial turtle position and direction
_t.x = saveX
_t.y = saveY
_t.dir = saveD
}
// nums assumed to be all non-negative
barChart(nums, size) {
// save intial turtle position and direction
var saveX = _t.x
var saveY = _t.y
var saveD = _t.dir
// find maximum
var max = 0
for (n in nums) if (n > max) max = n
// scale to fit within a square with sides 'size' and draw chart
var barWidth = (size / nums.count).floor
var startX = _w / 2 + 20
var startY = _h / 2
for (i in 0...nums.count) {
var barHeight = (nums[i] * size / max).round
_t.drawRect(startX, startY - barHeight, barWidth, barHeight)
startX = startX + barWidth
}
// restore intial turtle position and direction
_t.x = saveX
_t.y = saveY
_t.dir = saveD
}
update() {}
draw(alpha) {}
}
var Game = Main.new(600, 600) |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Scala | Scala | val (p , robot)= (component.location, new Robot())
robot.mouseMove(p.getX().toInt, p.getY().toInt) //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
robot.mouseRelease(InputEvent.BUTTON1_MASK) |
|
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Tcl | Tcl | # Simulate a full click cycle: button down and up
event generate .okBtn <ButtonPress-1> -x 5 -y 5
event generate .okBtn <ButtonRelease-1> -x 5 -y 5 |
|
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 | #BBC_BASIC | BBC BASIC | DIM node{pNext%, iData%}
|
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 | #Bracmat | Bracmat | link =
(next=)
(data=) |
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
| #ALGOL_68 | ALGOL 68 | MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next);
STRINGLIST list := ("Big",
LOC STRINGLIST := ("fjords",
LOC STRINGLIST := ("vex",
LOC STRINGLIST := ("quick",
LOC STRINGLIST := ("waltz",
LOC STRINGLIST := ("nymph",NIL))))));
REF STRINGLIST node := list;
WHILE node ISNT REF STRINGLIST(NIL) DO
print((value OF node, space));
node := next OF node
OD;
print(newline) |
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
| #ALGOL_W | ALGOL W | begin
% record type to hold a singly linked list of integers %
record ListI ( integer iValue; reference(ListI) next );
% inserts a new value after the specified element of a list %
procedure insert( reference(ListI) value list
; integer value newValue
) ;
next(list) := ListI( newValue, next(list) );
% declare variables to hold the list %
reference(ListI) head, pos;
% create a list of integers %
head := ListI( 1701, ListI( 9000, ListI( 42, ListI( 90210, null ) ) ) );
% insert a new value into the list %
insert( next(head), 4077 );
% traverse the list %
pos := head;
while pos not = null do begin
write( iValue(pos) );
pos := next(pos);
end;
end. |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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 - Insert after 01/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/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
| #8th | 8th |
f:stdin f:getline
"Sleeping..." . cr
eval sleep
"Awake!" . cr bye
|
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sleep64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
.equ SLEEP, 0x65 // Linux syscall
.equ BUFFERSIZE, 100
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessQuest: .asciz "Enter the time to sleep in seconds : "
szMessError: .asciz "Error occured.\n"
szMessSleep: .asciz "Sleeping Zzzzzzz.\n"
szMessAwake: .asciz "Awake!!!\n"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
ZonesAttente:
qSecondes: .skip 8
qMicroSecondes: .skip 8
ZonesTemps: .skip 16
sBuffer: .skip BUFFERSIZE
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszMessQuest // display invite message
bl affichageMess
mov x0,STDIN // input standard linux
ldr x1,qAdrsBuffer
mov x2,BUFFERSIZE
mov x8,READ // read input string
svc 0
cmp x0,0 // read error ?
ble 99f
//
ldr x0,qAdrsBuffer // buffer address
bl conversionAtoD // conversion string in number in x0
ldr x1,qAdrqSecondes
str x0,[x1] // store second number in area
ldr x0,qAdrszMessSleep // display sleeping message
bl affichageMess
ldr x0,qAdrZonesAttente // delay area
ldr x1,qAdrZonesTemps //
mov x8,#SLEEP // call system SLEEP
svc 0
cmp x0,#0 // error sleep ?
blt 99f
ldr x0,qAdrszMessAwake // display awake message
bl affichageMess
mov x0, #0 // return code
b 100f
99: // display error message
ldr x0,qAdrszMessError
bl affichageMess
mov x0, 1 // return code
100: // standard end of the program
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessQuest: .quad szMessQuest
qAdrszMessError: .quad szMessError
qAdrszMessSleep: .quad szMessSleep
qAdrszMessAwake: .quad szMessAwake
qAdrqSecondes: .quad qSecondes
qAdrZonesAttente: .quad ZonesAttente
qAdrZonesTemps: .quad ZonesTemps
qAdrsBuffer: .quad sBuffer
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* 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.
| #Sidef | Sidef | func bubble_sort(arr) {
loop {
var swapped = false
{ |i|
if (arr[i] > arr[i+1]) {
arr[i, i+1] = arr[i+1, i]
swapped = true
}
} << ^arr.end
swapped || break
}
return arr
} |
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.
| #Tcl | Tcl | package require TclOO
# This is a metaclass, a class that defines the behavior of other classes
oo::class create singleton {
superclass oo::class
variable object
unexport create ;# Doesn't make sense to have named singletons
method new args {
if {![info exists object]} {
set object [next {*}$args]
}
return $object
}
}
singleton create example {
method counter {} {
my variable count
return [incr count]
}
} |
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.
| #Tern | Tern | module Singleton {
speak() {
println("I am a singleton");
}
}
Singleton.speak(); |
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).
| #Scala | Scala | import java.awt.Robot
import java.awt.event.KeyEvent
/** Keystrokes when this function is executed will go to whatever application has focus at the time.
* Special cases may need to be made for certain symbols, but most of
* the VK values in KeyEvent map to the ASCII values of characters.
*/
object Keystrokes extends App {
def keystroke(str: String) {
val robot = new Robot()
for (ch <- str) {
if (Character.isUpperCase(ch)) {
robot.keyPress(KeyEvent.VK_SHIFT)
robot.keyPress(ch)
robot.keyRelease(ch)
robot.keyRelease(KeyEvent.VK_SHIFT)
} else {
val upCh = Character.toUpperCase(ch)
robot.keyPress(upCh)
robot.keyRelease(upCh)
}
}
}
keystroke(args(0))
} |
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. | #Yabasic | Yabasic | // Rosetta Code problem: http://rosettacode.org/wiki/Simple_turtle_graphics
// Adapted from Python to Yabasic by Galileo, 01/2022
import turtle
sub rectang(width, height)
local i
for i = 1 to 2
move(height)
turn(-90)
move(width)
turn(-90)
next
end sub
sub square(size)
rectang(size, size)
end sub
sub triang(size)
local i
for i = 1 to 3
move(size)
turn(120)
next
end sub
sub house(size)
turn(180)
square(size)
triang(size)
turn(180)
end sub
sub barchart(lst$, size)
local t$(1), t(1), n, m, i, scale, width
n = token(lst$, t$())
redim t(n)
for i = 1 to n
t(i) = val(t$(i))
if t(i) > m m = t(i)
next
scale = size/m
width = size/n
for i = 1 to n
rectang(t(i)*scale, width)
pen(false)
move(width)
pen(true)
next
pen(false)
move(-size)
pen(true)
end sub
startTurtle()
color 255, 255, 255
turn(90)
house(150)
pen(false)
move(10)
pen(true)
barchart("0.5 0.333 2 1.3 0.5", 200) |
http://rosettacode.org/wiki/Simulate_input/Mouse | Simulate input/Mouse | #Wren | Wren | /* simulate_input_mouse.wren */
var KeyPressMask = 1 << 0
var ButtonPressMask = 1 << 2
var Button1Mask = 1 << 8
var ExposureMask = 1 << 15
var Button1 = 1
var KeyPress = 2
var ButtonPress = 4
var Expose = 12
var ClientMessage = 33
var XK_a = 0x0061
var XK_q = 0x0071
var XK_Escape = 0xff1b
foreign class XGC {
construct default(display, screenNumber) {}
}
foreign class XColormap {
construct default(display, screenNumber) {}
}
foreign class XColor {
construct new() {}
foreign pixel
}
// XEvent is a C union, not a struct, so we amalgamate the properties
foreign class XEvent {
construct new() {} // creates the union and returns a pointer to it
foreign eventType // gets type field, common to all union members
foreign eventType=(et) // sets type field
foreign button // gets xbutton.button
foreign button=(b) // sets xbutton.button
foreign state=(st) // sets xbutton.state
foreign sameScreen=(ss) // sets xbutton.same_screen
foreign dataL // gets xclient.data.l (data is a union)
}
foreign class XDisplay {
construct openDisplay(displayName) {}
foreign defaultScreen()
foreign rootWindow(screenNumber)
foreign blackPixel(screenNumber)
foreign whitePixel(screenNumber)
foreign selectInput(w, eventMask)
foreign mapWindow(w)
foreign closeDisplay()
foreign nextEvent(eventReturn)
foreign createSimpleWindow(parent, x, y, width, height, borderWidth, border, background)
foreign drawString(d, gc, x, y, string, length)
foreign storeName(w, windowName)
foreign flush()
foreign internAtom(atomName, onlyIfExists)
foreign setWMProtocols(w, protocols, count)
foreign sendEvent(w, propogate, eventMask, eventSend)
foreign destroyWindow(w)
foreign parseColor(colormap, spec, exactDefReturn)
foreign allocColor(colormap, screenInOut)
foreign setWindowBackground(w, backgroundPixel)
foreign clearArea(w, x, y, width, height, exposures)
}
class X {
foreign static lookupKeysym(keyEvent, index)
}
/* open connection with the server */
var xd = XDisplay.openDisplay("")
if (xd == 0) {
System.print("Cannot open display.")
return
}
var s = xd.defaultScreen()
/* create window */
var w = xd.createSimpleWindow(xd.rootWindow(s), 10, 10, 350, 250, 1, xd.blackPixel(s), xd.whitePixel(s))
xd.storeName(w, "Simulate mouse press")
var white = true // current background color
/* select kind of events we are interested in */
xd.selectInput(w, ExposureMask | KeyPressMask | ButtonPressMask)
/* map (show) the window */
xd.mapWindow(w)
xd.flush()
/* default graphics context */
var gc = XGC.default(xd, s)
/* connect the close button in the window handle */
var wmDeleteWindow = xd.internAtom("WM_DELETE_WINDOW", true)
xd.setWMProtocols(w, [wmDeleteWindow], 1)
/* create color green */
var green = XColor.new()
var colormap = XColormap.default(xd, s)
xd.parseColor(colormap, "#00FF00", green)
xd.allocColor(colormap, green)
/* event loop */
var e = XEvent.new()
while (true) {
xd.nextEvent(e)
var et = e.eventType
if (et == Expose) {
/* draw or redraw the window */
var msg1 = "Press the 'a' key to switch the background color"
var msg2 = "between white and green."
xd.drawString(w, gc, 10, 20, msg1, msg1.count)
xd.drawString(w, gc, 10, 35, msg2, msg2.count)
} else if (et == ButtonPress) {
System.write("\nButtonPress event received, ")
if (white) {
System.print("switching from white to green")
xd.setWindowBackground(w, green.pixel)
} else {
System.print("switching from green to white")
xd.setWindowBackground(w, xd.whitePixel(s))
}
xd.clearArea(w, 0, 0, 0, 0, true)
white = !white
} else if (et == ClientMessage) {
/* delete window event */
if (e.dataL[0] == wmDeleteWindow) break
} else if (et == KeyPress) {
System.print("\nKeyPress event received")
/* exit if q or escape are pressed */
var keysym = X.lookupKeysym(e, 0)
if (keysym == XK_q || keysym == XK_Escape) {
break
} else if (keysym == XK_a) {
/* if a is pressed, manufacture a ButtonPress event and send it to the window */
System.print("> Key 'a' pressed, sending ButtonPress event")
var e2 = XEvent.new()
e2.eventType = ButtonPress
e2.state = Button1Mask
e2.button = Button1
e2.sameScreen = true
xd.sendEvent(w, true, ButtonPressMask, e2)
} else {
System.print("> Key other than 'a' pressed, not processed")
}
}
}
xd.destroyWindow(w)
/* close connection to server */
xd.closeDisplay() |
|
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 | #C | C | struct link {
struct link *next;
int data;
}; |
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 | #C.23 | C# | class LinkedListNode
{
public int Value { get; set; }
public LinkedListNode Next { get; set; }
// A constructor is not necessary, but could be useful.
public Link(int value, LinkedListNode next = null)
{
Item = value;
Next = next;
}
} |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program afficheList.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"
/* datas message display */
szMessResult: .ascii "Element No :"
sNumElement: .space 12,' '
.ascii " value : "
sValue: .space 12,' '
.asciz "\n"
/* UnInitialized data */
.bss
lList1: .skip llist_fin * NBELEMENTS @ list memory place
/* code section */
.text
.global main
main:
ldr r0,iAdrlList1
mov r1,#0 @ list init
str r1,[r0,#llist_next]
ldr r0,iAdrszMessInitListe
bl affichageMess
ldr r0,iAdrlList1
mov r1,#2
bl insertElement @ add element value 2
ldr r0,iAdrlList1
mov r1,#5
bl insertElement @ add element value 5
@ @ display elements of list
ldr r3,iAdrlList1
mov r2,#0 @ ident element
1:
ldr r0,[r3,#llist_next] @ end list ?
cmp r0,#0
beq 100f @ yes
add r2,#1
mov r0,r2 @ display No element and value
ldr r1,iAdrsNumElement
bl conversion10S
ldr r0,[r3,#llist_value]
ldr r1,iAdrsValue
bl conversion10S
ldr r0,iAdrszMessResult
bl affichageMess
ldr r3,[r3,#llist_next] @ next element
b 1b @ and loop
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
iAdrszMessResult: .int szMessResult
iAdrsNumElement: .int sNumElement
iAdrsValue: .int sValue
/******************************************************************/
/* insert element at end of list */
/******************************************************************/
/* r0 contains the address of the list */
/* r1 contains the value of element */
/* r0 returns address of element or - 1 if error */
insertElement:
push {r1-r3,lr} @ save registers
mov r2,#llist_fin * NBELEMENTS
add r2,r0 @ compute address end list
1: @ start loop
ldr r3,[r0,#llist_next] @ load next pointer
cmp r3,#0 @ = zero
movne r0,r3 @ no -> loop with pointer
bne 1b
add r3,r0,#llist_fin @ yes -> compute next free address
cmp r3,r2 @ > list end
movge r0,#-1 @ yes -> error
bge 100f
str r3,[r0,#llist_next] @ store next address in current pointer
str r1,[r0,#llist_value] @ store element value
mov r1,#0
str r1,[r3,#llist_next] @ init next pointer in next address
100:
pop {r1-r3,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* 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
/***************************************************/
/* Converting a register to a signed decimal */
/***************************************************/
/* r0 contains value and r1 area address */
conversion10S:
push {r0-r4,lr} @ save registers
mov r2,r1 @ debut zone stockage
mov r3,#'+' @ par defaut le signe est +
cmp r0,#0 @ negative number ?
movlt r3,#'-' @ yes
mvnlt r0,r0 @ number inversion
addlt r0,#1
mov r4,#10 @ length area
1: @ start loop
bl divisionpar10U
add r1,#48 @ digit
strb r1,[r2,r4] @ store digit on area
sub r4,r4,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0
bne 1b
strb r3,[r2,r4] @ store signe
subs r4,r4,#1 @ previous position
blt 100f @ if r4 < 0 -> end
mov r1,#' ' @ space
2:
strb r1,[r2,r4] @store byte space
subs r4,r4,#1 @ previous position
bge 2b @ loop if r4 > 0
100:
pop {r0-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
|
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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 insertList64.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"
sZoneConv: .skip 100
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
lList1: .skip llist_fin * NBELEMENTS // list memory place
/*******************************************/
/* 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
//
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/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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 insert-after (x e xs)
(cond ((endp xs)
nil)
((equal x (first xs))
(cons (first xs)
(cons e (rest xs))))
(t (cons (first xs)
(insert-after x e (rest xs)))))) |
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
| #Action.21 | Action! | BYTE RTCLOK1=$13
BYTE RTCLOK2=$14
BYTE PALNTSC=$D014
PROC Wait(CARD frames)
BYTE lsb=frames,msb=frames+1
;wait lsb of frames
lsb==+RTCLOK2
WHILE lsb#RTCLOK2 DO OD
;wait msb of 256*frames
WHILE msb>0
DO
WHILE lsb=RTCLOK2 DO OD
WHILE lsb#RTCLOK2 DO OD
msb==-1
OD
RETURN
CARD FUNC GetFrame()
CARD res
BYTE lsb=res,msb=res+1
lsb=RTCLOK2
msb=RTCLOK1
RETURN (res)
CARD FUNC MsToFrames(CARD ms)
CARD res
IF PALNTSC=15 THEN
res=ms/60
ELSE
res=ms/50
FI
RETURN (res)
CARD FUNC FramesToMs(CARD frames)
CARD res
IF PALNTSC=15 THEN
res=frames*60
ELSE
res=frames*50
FI
RETURN (res)
PROC Main()
CARD ARRAY data=[1 5 10 50 100 500]
CARD beg,end,diff,diffMs,delay,delayMs
BYTE i
FOR i=0 TO 5
DO
delay=data(i)
delayMs=FramesToMs(delay)
PrintF("Wait %U frames / %U ms...%E",delay,delayMs)
beg=GetFrame()
Wait(delay)
end=GetFrame()
diff=end-beg
diffMs=FramesToMs(diff)
PrintF("Frame number at begin %U%E",beg)
PrintF("Frame number at end %U%E",end)
PrintF("Waited %U-%U=%U frames / %U ms%E%E",end,beg,diff,diffMs)
OD
RETURN |
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
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
procedure Sleep is
In_Val : Float;
begin
Get(In_Val);
Put_Line("Sleeping...");
delay Duration(In_Val);
Put_Line("Awake!");
end Sleep; |
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.
| #Simula | Simula | BEGIN
PROCEDURE BUBBLESORT(A); NAME A; INTEGER ARRAY A;
BEGIN
INTEGER LOW, HIGH, I;
BOOLEAN SWAPPED;
PROCEDURE SWAP(I, J); INTEGER I, J;
BEGIN
INTEGER TEMP;
TEMP := A(I); A(I) := A(J); A(J) := TEMP;
END**OF**SWAP;
LOW := LOWERBOUND(A, 1);
HIGH := UPPERBOUND(A, 1);
SWAPPED := TRUE;
WHILE SWAPPED DO
BEGIN
SWAPPED := FALSE;
FOR I := LOW + 1 STEP 1 UNTIL HIGH DO
BEGIN
COMMENT IF THIS PAIR IS OUT OF ORDER ;
IF A(I - 1) > A(I) THEN
BEGIN
COMMENT SWAP THEM AND REMEMBER SOMETHING CHANGED ;
SWAP(I - 1, I);
SWAPPED := TRUE;
END;
END;
END;
END**OF**BUBBLESORT;
INTEGER ARRAY A(1:10);
INTEGER I, N;
I := 1;
FOR N := 6, 8, 5, 9, 3, 2, 2, 1, 4, 7 DO
BEGIN
A(I) := N; I := I + 1;
END;
BUBBLESORT(A);
FOR I:= 1 STEP 1 UNTIL 10 DO
OUTINT(A(I), 5);
OUTIMAGE;
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.
| #Vala | Vala | public class Singleton : Object {
static Singleton? instance;
// Private constructor
Singleton() {
}
// Public constructor
public static Singleton get_instance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
void main() {
Singleton a = Singleton.get_instance();
Singleton b = Singleton.get_instance();
if (a == b) {
print("Equal.\n");
}
} |
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).
| #Tcl | Tcl | set key "x"
event generate $target <Key-$key> |
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).
| #VBScript | VBScript | Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "{Down}{F2}"
WScript.Sleep 1000 ' one-second delay
WshShell.SendKeys "{Left}{Left}{BkSp}{BkSp}Some text here.~" ' ~ -> Enter |
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 | #C.2B.2B | C++ | struct link
{
link* next;
int data;
}; |
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 | #Clean | Clean | import StdMaybe
:: Link t = { next :: Maybe (Link t), data :: t } |
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
| #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 _ => ()
(*------------------------------------------------------------------*)
(* For simplicity, the Rosetta Code linear list traverse-and-print
routine will be specifically for lists of ‘int’. *)
(* Some things that will be needed. *)
#include "share/atspre_staload.hats"
(* The list is passed by value and will be preserved with the same
type. *)
extern fun
rclist_int_traverse_and_print
{m : int} (* ‘for all list lengths m’ *)
(lst : !rclist_vt (int, m) >> (* ! = pass by value *)
(* The new type will be the same as the old
type. *)
rclist_vt (int, m)) : void
implement
rclist_int_traverse_and_print {m} (lst) =
{
(* A recursive nested function that traverses the list, printing
elements along the way. *)
fun
traverse {k : int | 0 <= k}
.<k>. (* Means: ‘k must uniformly decrease towards zero.’
If so, that is proof that ‘find’ terminates. *)
(lst : !rclist_vt (int, k) >> rclist_vt (int, k)) :
void =
case+ lst of
| rclist_vt_nil () => () (* End of list. *)
| rclist_vt_cons (head, tail) =>
begin
println! (head);
traverse tail
end
(* The following is needed to prove that the initial k above
satisfies 0 <= k. *)
prval _ = lemma_rclist_vt_param lst
val _ = traverse lst
}
(* Now let’s try it. *)
(* Some convenient notation. *)
#define NIL rclist_vt_nil ()
#define :: rclist_vt_cons
overload traverse_and_print with rclist_int_traverse_and_print
val A = 123
val B = 789
val C = 456
val lst = A :: C :: B :: NIL
val () = traverse_and_print lst
(*------------------------------------------------------------------*)
implement
main0 () = () |
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
| #AutoHotkey | AutoHotkey | a = 1
a_next = b
b = 2
b_next = c
c = 3
traverse("a")
return
traverse(element)
{
MsgBox % element . "= " . %element%
name := element . "_next"
while, %name%
{
element := %name%
msgbox % %name% . "= " . %element%
name := %name% . "_next"
}
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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 insert(node:Node):void
{
node.link = link;
link = node;
}
}
} |
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
| #Aime | Aime | o_text("Sleeping...\n");
# Sleep X seconds
sleep(atoi(argv(1)));
# Sleep X microseconds
#usleep(atoi(argv(1)));
o_text("Awake!\n"); |
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
| #ALGOL_68 | ALGOL 68 | # using ping to sleep #
INT milliseconds = read int; # ping uses milliseconds #
print ("Sleeping...");
VOID (system ("ping 0.0.0.1 -n 1 -w " + whole (milliseconds, 0) + " >NUL"));
# 0.0.0.1 is an invalid IP address and cannot be used, so this will never conflict with a real IP address #
# ping -n gives number of tries, -w timeout, and >NUL deletes output so the user does not see it #
print (new line);
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.
| #Smalltalk | Smalltalk | |item swap itemCount hasChanged|
item := #(1 4 5 6 10 8 7 61 0 -3) copy.
swap :=
[:indexOne :indexTwo|
|temp|
temp := item at: indexOne.
item at: indexOne put: (item at: indexTwo).
item at: indexTwo put: temp].
itemCount := item size.
[hasChanged := false.
itemCount := itemCount - 1.
1 to: itemCount do:
[:index |
(item at: index) > (item at: index + 1) ifTrue:
[swap value: index value: index + 1.
hasChanged := true]].
hasChanged] whileTrue. |
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.
| #Wren | Wren | class Singleton {
// Returns the singleton. If it hasn't been created, creates it first.
static instance { __instance == null ? __instance = Singleton.new_() : __instance }
// Private constructor.
construct new_() {}
// instance method
speak() { System.print("I'm a singleton.") }
}
var s1 = Singleton.instance
var s2 = Singleton.instance
System.print("s1 and s2 are same object = %(Object.same(s1, s2))")
s1.speak() // call instance method |
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).
| #Wren | Wren | /* simulate_input_keyboard.wren */
import "random" for Random
var KeyPressMask = 1 << 0
var ShiftMask = 1 << 0
var ButtonPressMask = 1 << 2
var ExposureMask = 1 << 15
var KeyPress = 2
var ButtonPress = 4
var Expose = 12
var ClientMessage = 33
var XK_q = 0x0071
var XK_Escape = 0xff1b
foreign class XGC {
construct default(display, screenNumber) {}
}
// XEvent is a C union, not a struct, so we amalgamate the properties
foreign class XEvent {
construct new() {} // creates the union and returns a pointer to it
foreign eventType // gets type field, common to all union members
foreign eventType=(et) // sets type field
foreign state=(st) // sets xkey.state
foreign keycode // gets xkey.keycode
foreign keycode=(kc) // sets xkey.keycode
foreign sameScreen=(ss) // sets xkey.same_screen
foreign dataL // gets xclient.data.l (data is a union)
}
foreign class XDisplay {
construct openDisplay(displayName) {}
foreign defaultScreen()
foreign rootWindow(screenNumber)
foreign blackPixel(screenNumber)
foreign whitePixel(screenNumber)
foreign selectInput(w, eventMask)
foreign mapWindow(w)
foreign closeDisplay()
foreign nextEvent(eventReturn)
foreign createSimpleWindow(parent, x, y, width, height, borderWidth, border, background)
foreign drawString(d, gc, x, y, string, length)
foreign storeName(w, windowName)
foreign flush()
foreign internAtom(atomName, onlyIfExists)
foreign setWMProtocols(w, protocols, count)
foreign sendEvent(w, propogate, eventMask, eventSend)
foreign destroyWindow(w)
}
class X {
foreign static lookupKeysym(keyEvent, index)
foreign static lookupString(eventStruct, bufferReturn, bytesBuffer, keysymReturn, statusInOut)
}
/* open connection with the server */
var xd = XDisplay.openDisplay("")
if (xd == 0) {
System.print("Cannot open display.")
return
}
var s = xd.defaultScreen()
/* create window */
var w = xd.createSimpleWindow(xd.rootWindow(s), 10, 10, 350, 250, 1, xd.blackPixel(s), xd.whitePixel(s))
xd.storeName(w, "Simulate keystrokes")
/* select kind of events we are interested in */
xd.selectInput(w, ExposureMask | KeyPressMask | ButtonPressMask)
/* map (show) the window */
xd.mapWindow(w)
xd.flush()
/* default graphics context */
var gc = XGC.default(xd, s)
/* connect the close button in the window handle */
var wmDeleteWindow = xd.internAtom("WM_DELETE_WINDOW", true)
xd.setWMProtocols(w, [wmDeleteWindow], 1)
/* event loop */
var e = XEvent.new()
var rand = Random.new()
while (true) {
xd.nextEvent(e)
var et = e.eventType
if (et == Expose) {
/* draw or redraw the window */
var msg1 = "Click in the window to generate"
var msg2 = "a random key press event"
xd.drawString(w, gc, 10, 20, msg1, msg1.count)
xd.drawString(w, gc, 10, 35, msg2, msg2.count)
} else if (et == ButtonPress) {
System.print("\nButtonPress event received")
/* manufacture a KeyPress event and send it to the window */
var e2 = XEvent.new()
e2.eventType = KeyPress
e2.state = ShiftMask
e2.keycode = 24 + rand.int(33)
e2.sameScreen = true
xd.sendEvent(w, true, KeyPressMask, e2)
} else if (et == ClientMessage) {
/* delete window event */
if (e.dataL[0] == wmDeleteWindow) break
} else if (et == KeyPress) {
/* handle key press */
System.print("\nKeyPress event received")
System.print("> Keycode: %(e.keycode)")
/* exit if q or escape are pressed */
var keysym = X.lookupKeysym(e, 0)
if (keysym == XK_q || keysym == XK_Escape) {
break
} else {
var buffer = List.filled(2, 0)
var nchars = X.lookupString(e, buffer, 2, 0, 0) // don't need the last 2 parameters
if (nchars == 1) {
var b = buffer[0]
if (b < 0) b = 256 + b
System.print("> Latin-1: %(b)")
if (b < 32 || (b >= 127 && b < 160)) {
System.print("> Key 'control character' pressed")
} else {
System.print("> Key '%(String.fromByte(b))' pressed")
}
}
}
}
}
xd.destroyWindow(w)
/* close connection to server */
xd.closeDisplay() |
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 | #Clojure | Clojure | (cons 1 (cons 2 (cons 3 nil))) ; =>(1 2 3) |
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 | #Common_Lisp | Common Lisp | (cons 1 (cons 2 (cons 3 nil)) => (1 2 3) |
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
| #Axe | Axe | LINK(L₁,1)→A
LINK(L₁+10,2)→B
LINK(L₁+50,3)→C
INSERT(A,B)
INSERT(A,C)
A→I
While I≠0
Disp VALUE(I)▶Dec,i
NEXT(I)→I
End |
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
| #BBC_BASIC | BBC BASIC | DIM node{pNext%, iData%}
DIM a{} = node{}, b{} = node{}, c{} = node{}
a.pNext% = b{}
a.iData% = 123
b.iData% = 789
c.iData% = 456
PROCinsert(a{}, c{})
PRINT "Traverse list:"
pnode% = a{}
REPEAT
!(^node{}+4) = pnode%
PRINT node.iData%
pnode% = node.pNext%
UNTIL pnode% = 0
END
DEF PROCinsert(here{}, new{})
new.pNext% = here.pNext%
here.pNext% = new{}
ENDPROC
|
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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 | with Ada.Unchecked_Deallocation;
-- Define the link type
procedure Singly_Linked is
type Link;
type Link_Access is access Link;
type Link is record
Data : Integer;
Next : Link_Access := null;
end record;
-- Instantiate the generic deallocator for the link type
procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access);
-- Define the procedure
procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is
begin
if Anchor /= null and Newbie /= null then
Newbie.Next := Anchor.Next;
Anchor.Next := Newbie;
end if;
end Insert_Append;
-- Create the link elements
A : Link_Access := new Link'(1, null);
B : Link_Access := new Link'(2, null);
C : Link_Access := new Link'(3, null);
-- Execute the program
begin
Insert_Append(A, B);
Insert_Append(A, C);
Free(A);
Free(B);
Free(C);
end Singly_Linked; |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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 | MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next);
STRINGLIST list := ("Big",
LOC STRINGLIST := ("fjords",
LOC STRINGLIST := ("vex",
LOC STRINGLIST := ("quick",
LOC STRINGLIST := ("waltz",
LOC STRINGLIST := ("nymph",NIL))))));
PROC insert = (REF STRINGLIST list, node)VOID: (
next OF node := next OF list;
next OF list := node
);
STRINGLIST very := ("VERY", NIL);
# EXAMPLE OF INSERTION #
insert(next OF next OF list, very );
REF STRINGLIST node := list;
WHILE REF STRINGLIST(node) ISNT NIL DO
print((value OF node, space));
node := next OF node
OD;
print((newline)) |
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
| #AntLang | AntLang | milliseconds: eval[input["How long should I sleep? "]] / eval = evil, but this is just a simple demo
echo["Sleeping..."]
sleep[milliseconds]
echo["Awake!"] |
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
| #Applesoft_BASIC | Applesoft BASIC | 10 POKE 768,169: POKE 770,76
20 POKE 771,168: POKE 772,252
30 INPUT "ENTER WAIT VALUE (1-256) : ";A
40 IF A < 1 OR A > 256 THEN 30
50 POKE 769,(A < 256) * A
60 LET C = (26 + 27 * A + 5 * A ^ 2) / 2
70 PRINT "WAIT FOR "C" CYCLES OR "
80 PRINT C * 14 / 14.318181" MICROSECONDS"
90 PRINT "SLEEPING": CALL 768: 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.
| #SNOBOL4 | SNOBOL4 | * # Sort array in place, return array
define('bubble(a,alen)i,j,ub,tmp') :(bubble_end)
bubble i = 1; ub = alen
outer gt(ub,1) :f(bdone)
j = 1
inner le(a<j>, a<j + 1>) :s(incrj)
tmp = a<j>
a<j> = a<j + 1>
a<j + 1> = tmp
incrj j = lt(j + 1,ub) j + 1 :s(inner)
ub = ub - 1 :(outer)
bdone bubble = a :(return)
bubble_end
* # Fill array with test data
str = '33 99 15 54 1 20 88 47 68 72'
output = str; arr = array(10)
floop i = i + 1; str span('0123456789') . arr<i> = :s(floop)
* # Test and display
bubble(arr,10); str = ''
sloop j = j + 1; str = str arr<j> ' ' :s(sloop)
output = trim(str)
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.
| #zkl | zkl | class [static] Borg{ var v }
b1 := Borg; b2 := Borg();
b1 == b2 //--> True
b1.v=123; b2.v.println(); //--> 123 |
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 | #D | D | struct SLinkedNode(T) {
T data;
typeof(this)* next;
}
void main() {
alias SLinkedNode!int N;
N* n = new N(10);
} |
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 | #Delphi | Delphi | Type
pOneWayList = ^OneWayList;
OneWayList = record
pData : pointer ;
Next : pOneWayList ;
end; |
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
| #C | C | struct link *first;
// ...
struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {
// access data, e.g. with iter->data
} |
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
| #C.23 | C# | var current = [head of list to traverse]
while(current != null)
{
// Do something with current.Value.
current = current.Next;
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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 | % inserts a new value after the specified element of a list %
procedure insert( reference(ListI) value list
; integer value newValue
) ;
next(list) := ListI( newValue, next(list) );
% 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 ) ) ) );
% insert a new value into the list %
insert( next(head), 4077 ); |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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 insertList.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"
/* datas message display */
szMessResult: .ascii "Element No :"
sNumElement: .space 12,' '
.ascii " value : "
sValue: .space 12,' '
.asciz "\n"
/* UnInitialized data */
.bss
lList1: .skip llist_fin * NBELEMENTS @ list memory place
/* code section */
.text
.global main
main:
ldr r0,iAdrlList1
mov r1,#0 @ list init
str r1,[r0,#llist_next]
ldr r0,iAdrszMessInitListe
bl affichageMess
ldr r0,iAdrlList1
mov r1,#2
bl insertElement @ add element value 2
ldr r0,iAdrlList1
mov r1,#5
bl insertElement @ add element value 5
ldr r3,iAdrlList1
mov r2,#0 @ ident element
1:
ldr r0,[r3,#llist_next] @ end list ?
cmp r0,#0
beq 100f @ yes
add r2,#1
mov r0,r2 @ display No element and value
ldr r1,iAdrsNumElement
bl conversion10S
ldr r0,[r3,#llist_value]
ldr r1,iAdrsValue
bl conversion10S
ldr r0,iAdrszMessResult
bl affichageMess
ldr r3,[r3,#llist_next] @ next element
b 1b @ and loop
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
iAdrszMessResult: .int szMessResult
iAdrsNumElement: .int sNumElement
iAdrsValue: .int sValue
/******************************************************************/
/* insert element at end of list */
/******************************************************************/
/* r0 contains the address of the list */
/* r1 contains the value of element */
/* r0 returns address of element or - 1 if error */
insertElement:
push {r1-r3,lr} @ save registers
mov r2,#llist_fin * NBELEMENTS
add r2,r0 @ compute address end list
1: @ start loop
ldr r3,[r0,#llist_next] @ load next pointer
cmp r3,#0 @ = zero
movne r0,r3 @ no -> loop with pointer
bne 1b
add r3,r0,#llist_fin @ yes -> compute next free address
cmp r3,r2 @ > list end
movge r0,#-1 @ yes -> error
bge 100f
str r3,[r0,#llist_next] @ store next address in current pointer
str r1,[r0,#llist_value] @ store element value
mov r1,#0
str r1,[r3,#llist_next] @ init next pointer in next address
100:
pop {r1-r3,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* 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
/***************************************************/
/* Converting a register to a signed decimal */
/***************************************************/
/* r0 contains value and r1 area address */
conversion10S:
push {r0-r4,lr} @ save registers
mov r2,r1 @ debut zone stockage
mov r3,#'+' @ par defaut le signe est +
cmp r0,#0 @ negative number ?
movlt r3,#'-' @ yes
mvnlt r0,r0 @ number inversion
addlt r0,#1
mov r4,#10 @ length area
1: @ start loop
bl divisionpar10U
add r1,#48 @ digit
strb r1,[r2,r4] @ store digit on area
sub r4,r4,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0
bne 1b
strb r3,[r2,r4] @ store signe
subs r4,r4,#1 @ previous position
blt 100f @ if r4 < 0 -> end
mov r1,#' ' @ space
2:
strb r1,[r2,r4] @store byte space
subs r4,r4,#1 @ previous position
bge 2b @ loop if r4 > 0
100:
pop {r0-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
|
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program sleepAsm.s */
/* Constantes */
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ SLEEP, 0xa2 @ Linux syscall
.equ BUFFERSIZE, 100
/* Initialized data */
.data
szMessQuest: .asciz "Enter the time to sleep in seconds : "
szMessError: .asciz "Error occured.\n"
szMessSleep: .asciz "Sleeping Zzzzzzz.\n"
szMessAwake: .asciz "Awake!!!\n"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
.align 4
ZonesAttente:
iSecondes: .skip 4
iMicroSecondes: .skip 4
ZonesTemps: .skip 8
sBuffer: .skip BUFFERSIZE
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessQuest @ display invite message
bl affichageMess
mov r0,#STDIN @ input standard linux
ldr r1,iAdrsBuffer
mov r2,#BUFFERSIZE
mov r7,#READ @ read input string
svc 0
cmp r0,#0 @ read error ?
ble 99f
@
ldr r0,iAdrsBuffer @ buffer address
bl conversionAtoD @ conversion string in number in r0
ldr r1,iAdriSecondes
str r0,[r1] @ store second number in area
ldr r0,iAdrszMessSleep @ display sleeping message
bl affichageMess
ldr r0,iAdrZonesAttente @ delay area
ldr r1,iAdrZonesTemps @
mov r7,#SLEEP @ call system SLEEP
svc 0
cmp r0,#0 @ error sleep ?
blt 99f
ldr r0,iAdrszMessAwake @ display awake message
bl affichageMess
mov r0, #0 @ return code
b 100f
99: @ display error message
ldr r0,iAdrszMessError
bl affichageMess
mov r0, #1 @ return code
100: @ standard end of the program
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessQuest: .int szMessQuest
iAdrszMessError: .int szMessError
iAdrszMessSleep: .int szMessSleep
iAdrszMessAwake: .int szMessAwake
iAdriSecondes: .int iSecondes
iAdrZonesAttente: .int ZonesAttente
iAdrZonesTemps: .int ZonesTemps
iAdrsBuffer: .int sBuffer
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* 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
/******************************************************************/
/* Convert a string to a number stored in a registry */
/******************************************************************/
/* r0 contains the address of the area terminated by 0 or 0A */
/* r0 returns a number */
conversionAtoD:
push {fp,lr} @ save 2 registers
push {r1-r7} @ save others registers
mov r1,#0
mov r2,#10 @ factor
mov r3,#0 @ counter
mov r4,r0 @ save address string -> r4
mov r6,#0 @ positive sign by default
mov r0,#0 @ initialization to 0
1: /* early space elimination loop */
ldrb r5,[r4,r3] @ loading in r5 of the byte located at the beginning + the position
cmp r5,#0 @ end of string -> end routine
beq 100f
cmp r5,#0x0A @ end of string -> end routine
beq 100f
cmp r5,#' ' @ space ?
addeq r3,r3,#1 @ yes we loop by moving one byte
beq 1b
cmp r5,#'-' @ first character is -
moveq r6,#1 @ 1 -> r6
beq 3f @ then move on to the next position
2: /* beginning of digit processing loop */
cmp r5,#'0' @ character is not a number
blt 3f
cmp r5,#'9' @ character is not a number
bgt 3f
/* character is a number */
sub r5,#48
ldr r1,iMaxi @ check the overflow of the register
cmp r0,r1
bgt 99f @ overflow error
mul r0,r2,r0 @ multiply par factor 10
add r0,r5 @ add to r0
3:
add r3,r3,#1 @ advance to the next position
ldrb r5,[r4,r3] @ load byte
cmp r5,#0 @ end of string -> end routine
beq 4f
cmp r5,#0x0A @ end of string -> end routine
beq 4f
b 2b @ loop
4:
cmp r6,#1 @ test r6 for sign
moveq r1,#-1
muleq r0,r1,r0 @ if negatif, multiply par -1
b 100f
99: /* overflow error */
ldr r0,=szMessErrDep
bl affichageMess
mov r0,#0 @ return zero if error
100:
pop {r1-r7} @ restaur other registers
pop {fp,lr} @ restaur 2 registers
bx lr @return procedure
/* constante program */
iMaxi: .int 1073741824
szMessErrDep: .asciz "Too large: overflow 32 bits.\n"
.align 4
|
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.
| #SPARK | SPARK | package Bubble
is
type Arr is array(Integer range <>) of Integer;
procedure Sort (A : in out Arr);
--# derives A from *;
end Bubble;
package body Bubble
is
procedure Sort (A : in out Arr)
is
Finished : Boolean;
Temp : Integer;
begin
if A'Last /= A'First then
loop
Finished := True;
for J in Integer range A'First .. A'Last - 1 loop
if A (J + 1) < A (J) then
Finished := False;
Temp := A (J + 1);
A (J + 1) := A (J);
A (J) := Temp;
end if;
end loop;
--# assert A'Last /= A'First;
exit when Finished;
end loop;
end if;
end Sort;
end Bubble;
|
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 | #E | E | interface LinkedList guards LinkedListStamp {}
def empty implements LinkedListStamp {
to null() { return true }
}
def makeLink(value :int, var next :LinkedList) {
def link implements LinkedListStamp {
to null() { return false }
to value() { return value }
to next() { return next }
to setNext(new) { next := new }
}
return link
} |
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 | #Elena | Elena | class Link
{
prop int Item;
prop Link Next;
constructor(int item, Link next)
{
Item := item;
Next := next
}
} |
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
| #C.2B.2B | C++ | #include <iostream>
#include <forward_list>
int main()
{
std::forward_list<int> list{1, 2, 3, 4, 5};
for (int e : list)
std::cout << e << std::endl;
} |
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
| #Clojure | Clojure | (doseq [x xs] (println x)) |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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 _ => ()
(*------------------------------------------------------------------*)
(* For simplicity, the Rosetta Code linear list insertion routine will
be specifically for lists of ‘int’. We shall not take advantage of
the template system. *)
(* Some things that will be needed. *)
#include "share/atspre_staload.hats"
(* The list is passed by reference and will be replaced by the new
list. The old list is invalidated. *)
extern fun
rclist_int_insert
{m : int} (* ‘for all list lengths m’ *)
(lst : &rclist_vt (int, m) >> (* & = pass by reference *)
(* The new type will be a list of the same
length (if no match were found) or a list
one longer. *)
[n : int | n == m || n == m + 1]
rclist_vt (int, n),
after : int,
x : int) :<!wrt> void
implement
rclist_int_insert {m} (lst, after, x) =
{
(* A recursive nested function that finds the matching element
and inserts the new node. *)
fun
find {k : int | 0 <= k}
.<k>. (* Means: ‘k must uniformly decrease towards zero.’
If so, that is proof that ‘find’ terminates. *)
(lst : &rclist_vt (int, k) >>
[j : int | j == k || j == k + 1]
rclist_vt (int, j),
after : int,
x : int) :<!wrt> void =
case+ lst of
| rclist_vt_nil () => () (* Not found. Do nothing *)
| @ rclist_vt_cons (head, tail) when head = after =>
{
val _ = tail := rclist_vt_cons (x, tail)
prval _ = fold@ lst (* I need this unfolding and refolding
stuff to make ‘tail’ a reference
rather than a value, so I can
assign to it. *)
}
| @ rclist_vt_cons (head, tail) =>
{
val _ = find (tail, after, x)
prval _ = fold@ lst
}
(* The following is needed to prove that the initial k above
satisfies 0 <= k. *)
prval _ = lemma_rclist_vt_param lst
val _ = find (lst, after, x)
}
(* Now let’s try it. *)
(* Some convenient notation. *)
#define NIL rclist_vt_nil ()
#define :: rclist_vt_cons
overload insert with rclist_int_insert
val A = 123
val B = 789
val C = 456
(* ‘var’ to make lst a mutable variable rather than a
value (‘val’). *)
var lst = A :: B :: NIL
(* Do the insertion. *)
val () = insert (lst, A, C)
fun
loop {k : int | 0 <= k} .<k>.
(p : !rclist_vt (int, k)) : void =
case+ p of
| NIL => ()
| head :: tail =>
begin
println! (head);
loop tail
end
prval () = lemma_rclist_vt_param lst
val () = loop lst
(*------------------------------------------------------------------*)
implement
main0 () = () |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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 | a = 1
a_next = b
b = 2
b_next = 0
c = 3
insert_after("c", "a")
Listvars
msgbox
return
insert_after(new, old)
{
local temp
temp := %old%_next
%old%_next := new
%new%_next := temp
} |
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
| #Arturo | Arturo | time: to :integer input "Enter number of milliseconds: "
print "Sleeping..."
pause time
print "Awake!" |
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
| #AutoHotkey | AutoHotkey | TrayTip, sleeping, sleeping
sleep, 2000 ; 2 seconds
TrayTip, awake, awake
Msgbox, 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.
| #Standard_ML | Standard ML | fun bubble_select [] = []
| bubble_select [a] = [a]
| bubble_select (a::b::xs) =
if b < a then b::(bubble_select(a::xs)) else a::(bubble_select(b::xs))
fun bubblesort [] = []
| bubblesort (x::xs) =bubble_select (x::(bubblesort xs))
|
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 | #Erlang | Erlang |
new( Data ) -> erlang:spawn( fun() -> loop( Data, nonext ) 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 | #Factor | Factor | TUPLE: linked-list data next ;
: <linked-list> ( data -- linked-list )
linked-list new swap >>data ; |
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
| #Common_Lisp | Common Lisp | (dolist (x list)
(print x)) |
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
| #Computer.2Fzero_Assembly | Computer/zero Assembly | start: LDA load
ADD car ; head of list
STA ldcar
ADD one
STA ldcdr
ldcar: NOP
STA value
ldcdr: NOP
BRZ done ; 0 == NIL
STA car
JMP start
done: LDA value
STP
load: LDA 0
value: 0
car: 28 ; head of list
one: 1
20,21: 6, 0
22,23: 2, 26
24,25: 5, 20
26,27: 3, 30
28,29: 1, 22
30,31: 4, 24 |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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
| #Axe | Axe | Lbl INSERT
{r₁+2}ʳ→{r₂+2}ʳ
r₂→{r₁+2}ʳ
r₁
Return |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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
| #BBC_BASIC | BBC BASIC | DIM node{pNext%, iData%}
DIM a{} = node{}, b{} = node{}, c{} = node{}
a.pNext% = b{}
a.iData% = 123
b.iData% = 789
c.iData% = 456
PROCinsert(a{}, c{})
END
DEF PROCinsert(here{}, new{})
new.pNext% = here.pNext%
here.pNext% = new{}
ENDPROC
|
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
| #AutoIt | AutoIt | #AutoIt Version: 3.2.10.0
$sleep_me=InputBox("Sleep", "Number of seconds to sleep", "10", "", -1, -1, 0, 0)
Dim $sleep_millisec=$sleep_me*1000
MsgBox(0,"Sleep","Sleeping for "&$sleep_me&" sec")
sleep ($sleep_millisec)
MsgBox(0,"Awake","... Awaking") |
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.
| #Stata | Stata | mata
function bubble_sort(a) {
n = length(a)
for (j = n; j >= 2; j--) {
q = 1
for (i = 2; i <= j; i++) {
if (a[i-1] > a[i]) {
q = 0
s = a[i-1]
a[i-1] = a[i]
a[i] = s
}
}
if (q) return
}
}
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 | #Fantom | Fantom |
class Node
{
const Int value // keep value fixed
Node? successor // allow successor to change, also, can be 'null', for end of list
new make (Int value, Node? successor := null)
{
this.value = value
this.successor = successor
}
}
|
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 | #Forth | Forth | 0 value numbers
: push ( n -- )
here swap numbers , , to numbers ; |
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
| #D | D | struct SLinkedNode(T) {
T data;
typeof(this)* next;
}
void main() {
import std.stdio;
alias N = SLinkedNode!int;
auto lh = new N(1, new N(2, new N(3, new N(4))));
for (auto p = lh; p; p = p.next)
write(p.data, " ");
writeln();
} |
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
| #Delphi | Delphi | uses system ;
type
// declare the list pointer type
plist = ^List ;
// declare the list type, a generic data pointer prev and next pointers
List = record
data : pointer ;
next : pList ;
end;
// since this task is just showing the traversal I am not allocating the memory and setting up the root node etc.
// Note the use of the carat symbol for de-referencing the pointer.
begin
// beginning to end
while not (pList^.Next = NIL) do pList := pList^.Next ;
end; |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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
| #C | C | void insert_append (struct link *anchor, struct link *newlink) {
newlink->next = anchor->next;
anchor->next = newlink;
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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
| #C.23 | C# | static void InsertAfter<T>(LinkedListNode<T> prev, T value)
{
prev.Next = new Link() { Value = value, Next = prev.Next };
} |
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
| #AWK | AWK |
# syntax: GAWK -f SLEEP.AWK [seconds]
BEGIN {
print("Sleeping...")
loop(ARGV[1])
print("Awake!")
exit(0)
}
function loop(seconds, t) {
# awk lacks a sleep mechanism, so simulate one by looping
t = systime()
while (systime() < t + seconds) {}
}
|
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
| #Axe | Axe | Disp "TIME:"
input→A
0→T
length(A)→L
For(I,1,L)
If {A}<'0' or {A}>'9'
Disp "NOT A NUMBER",i
Return
End
T*10+{A}-'0'→T
A++
End
Disp "SLEEPING...",i
Pause T
Disp "AWAKE",i |
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.
| #Swift | Swift | func bubbleSort<T:Comparable>(list:inout[T]) {
var done = false
while !done {
done = true
for i in 1..<list.count {
if list[i - 1] > list[i] {
(list[i], list[i - 1]) = (list[i - 1], list[i])
done = false
}
}
}
}
var list1 = [3, 1, 7, 5, 2, 5, 3, 8, 4]
print(list1)
bubbleSort(list: &list1)
print(list1) |
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 | #Fortran | Fortran | type node
real :: data
type( node ), pointer :: next => null()
end type node
!
!. . . .
!
type( node ) :: head |
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 | #FreeBASIC | FreeBASIC | type ll_int
n as integer
nxt as ll_int ptr
end type |
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
| #Dyalect | Dyalect | type List = Cons(value, tail) or Nil()
with Lookup
static func List.FromArray(xs) {
var list = List.Nil()
var len = xs.Length()
for i in (len-1)^-1..0 {
list = List.Cons(xs[i], list)
}
return list
}
func List.Iterate() {
var xs = this
do {
match xs {
Cons(value, tail) => {
yield value
xs = tail
},
Nil() => {
yield break
}
}
} while true
}
var xs = List.FromArray([1..10])
for x in xs {
print(x)
} |
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
| #E | E | var linkedList := [1, [2, [3, [4, [5, [6, [7, null]]]]]]]
while (linkedList =~ [value, next]) {
println(value)
linkedList := next
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
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
| #C.2B.2B | C++ | template<typename T> void insert_after(link<T>* list_node, link<T>* new_node)
{
new_node->next = list_node->next;
list_node->next = new_node;
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.