Works with: Visual Basic version VB6 Standard
'Knapsack problem/0-1 - 12/02/2017
Option Explicit
Const maxWeight = 400
Dim DataList As Variant
Dim xList(64, 3) As Variant
Dim nItems As Integer
Dim s  As String, xss As String
Dim xwei As Integer, xval As Integer, nn As Integer

Private Sub Form_Load()
    Dim i As Integer, j As Integer
    DataList = Array("map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160, _
           "glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40, _
           "cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30, _
           "T-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10, _
           "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _
           "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50)
    nItems = (UBound(DataList) + 1) / 3
    j = 0
    For i = 1 To nItems
        xList(i, 1) = DataList(j)
        xList(i, 2) = DataList(j + 1)
        xList(i, 3) = DataList(j + 2)
        j = j + 3
    Next i
    For i = 1 To nItems
        xListBox.AddItem xList(i, 1)
    Next i
End Sub

Private Sub cmdOK_Click()
    Dim i As Integer, j As Integer
    For i = 1 To xListBox.ListCount
        xListBox.RemoveItem 0
    Next i
    s = ""
    For i = 1 To nItems
        s = s & Chr(i)
    Next
    nn = 0
    Call ChoiceBin(1, "")
    For i = 1 To Len(xss)
        j = Asc(Mid(xss, i, 1))
        xListBox.AddItem xList(j, 1)
    Next i
    xListBox.AddItem "*Total* " & xwei & " " & xval
End Sub

Private Sub ChoiceBin(n As String, ss As String)
    Dim r As String
    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer
    Dim ipct As Integer
    If n = Len(s) + 1 Then
        iwei = 0: ival = 0
        For i = 1 To Len(ss)
            j = Asc(Mid(ss, i, 1))
            iwei = iwei + xList(j, 2)
            ival = ival + xList(j, 3)
        Next
        If iwei <= maxWeight And ival > xval Then
            xss = ss: xwei = iwei: xval = ival
        End If
    Else
        r = Mid(s, n, 1)
        Call ChoiceBin(n + 1, ss & r)
        Call ChoiceBin(n + 1, ss)
    End If
End Sub 'ChoiceBin

The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.


The code takes a string input and converts it into audible Morse code, which is then sent to an audio device such as a PC speaker. It handles unknown characters by either ignoring them or indicating them with a different pitch. The code is compatible with both VBA and VB6 without any modifications.


Works with: Visual Basic version VB6 Standard
Debug.Print Environ$("PATH")

"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system."


Analytic[edit]

select round ( exp ( sum (ln ( ( 1 + sqrt( 5 ) ) / 2)
        ) over ( order by level ) ) / sqrt( 5 ) ) fibo
from dual
connect by level <= 10;
       FIB
----------
         1
         1
         2
         3
         5
         8
        13
        21
        34
        55

10 rows selected.

select round ( power( ( 1 + sqrt( 5 ) ) / 2, level ) / sqrt( 5 ) ) fib
from dual
connect by level <= 10;
       FIB
----------
         1
         1
         2
         3
         5
         8
        13
        21
        34
        55

10 rows selected.

Recursive[edit]
Works with: Oracle

SQL> with fib(e,f) as (select 1, 1 from dual union all select e+f,e from fib where e <= 55) select f from fib;

         F
----------
         1
         1
         2
         3
         5
         8
        13
        21
        34
        55

10 rows selected.
Works with: PostgreSQL
CREATE FUNCTION fib(n int) RETURNS numeric AS $$
    -- This recursive with generates endless list of Fibonacci numbers.
    WITH RECURSIVE fibonacci(current, previous) AS (
        -- Initialize the current with 0, so the first value will be 0.
        -- The previous value is set to 1, because its only goal is not
        -- special casing the zero case, and providing 1 as the second
        -- number in the sequence.
        --
        -- The numbers end with dots to make them numeric type in
        -- Postgres. Numeric type has almost arbitrary precision
        -- (technically just 131,072 digits, but that's good enough for
        -- most purposes, including calculating huge Fibonacci numbers)
        SELECT 0., 1.
    UNION ALL
        -- To generate Fibonacci number, we need to add together two
        -- previous Fibonacci numbers. Current number is saved in order
        -- to be accessed in the next iteration of recursive function.
        SELECT previous + current, current FROM fibonacci
    )
    -- The user is only interested in current number, not previous.
    SELECT current FROM fibonacci
    -- We only need one number, so limit to 1
    LIMIT 1
    -- Offset the query by the requested argument to get the correct
    -- position in the list.
    OFFSET n
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE;

"Generates the nth Fibonacci number using either an iterative or recursive approach. The function also optionally supports negative n values by inversely applying the Fibonacci sequence formula."


Works with: MS SQL
--Create the original array (table #nos) with numbers from 1 to 10
create table #nos (v int)
declare @n int set @n=1
while @n<=10 begin insert into #nos values (@n) set @n=@n+1 end

--Select the subset that are even into the new array (table #evens)
select v into #evens from #nos where v % 2 = 0

-- Show #evens
select * from #evens

-- Clean up so you can edit and repeat:
drop table #nos
drop table #evens
'Works with: MySQL
create temporary table nos (v int);
insert into nos values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
create temporary table evens (v int);
insert into evens select v from nos where v%2=0;
select * from evens order by v; /*2,4,6,8,10*/
drop table nos;
drop table evens;

create temporary table evens select * from nos where v%2=0;

"Selects specific elements from an array into a new array, specifically even numbers. Alternatively, it can also modify the original array destructively."


--Clean up previous run
IF EXISTS (SELECT *
           FROM   SYS.TYPES
           WHERE  NAME = 'FairPlayTable')
  DROP TYPE FAIRPLAYTABLE

--Set Types
CREATE TYPE FAIRPLAYTABLE AS TABLE (LETTER VARCHAR(1), COLID INT, ROWID INT)

GO

--Configuration Variables
DECLARE @KEYWORD VARCHAR(25) = 'CHARLES' --Keyword for encryption
DECLARE @INPUT VARCHAR(MAX) = 'Testing Seeconqz' --Word to be encrypted
DECLARE @Q INT = 0 -- Q removed?
DECLARE @ENCRYPT INT = 1 --Encrypt?
--Setup Variables
DECLARE @WORDS TABLE
  (
     WORD_PRE  VARCHAR(2),
     WORD_POST VARCHAR(2)
  )
DECLARE @T_TABLE FAIRPLAYTABLE
DECLARE @NEXTLETTER CHAR(1)
DECLARE @WORD VARCHAR(2),
        @COL1 INT,
        @COL2 INT,
        @ROW1 INT,
        @ROW2 INT,
        @TMP  INT
DECLARE @SQL     NVARCHAR(MAX) = '',
        @COUNTER INT = 1,
        @I       INT = 1
DECLARE @COUNTER_2 INT = 1

SET @INPUT = REPLACE(@INPUT, ' ', '')
SET @KEYWORD = UPPER(@KEYWORD)

DECLARE @USEDLETTERS VARCHAR(MAX) = ''
DECLARE @TESTWORDS VARCHAR(2),
        @A         INT = 0

WHILE @COUNTER_2 <= 5
  BEGIN
      WHILE @COUNTER <= 5
        BEGIN
            IF LEN(@KEYWORD) > 0
              BEGIN
                  SET @NEXTLETTER = LEFT(@KEYWORD, 1)
                  SET @KEYWORD = RIGHT(@KEYWORD, LEN(@KEYWORD) - 1)

                  IF CHARINDEX(@NEXTLETTER, @USEDLETTERS) = 0
                    BEGIN
                        INSERT INTO @T_TABLE
                        SELECT @NEXTLETTER,
                               @COUNTER,
                               @COUNTER_2

                        SET @COUNTER = @COUNTER + 1
                        SET @USEDLETTERS = @USEDLETTERS + @NEXTLETTER
                    END
              END
            ELSE
              BEGIN
                  WHILE 1 = 1
                    BEGIN
                        IF CHARINDEX(CHAR(64 + @I), @USEDLETTERS) = 0
                           AND NOT ( CHAR(64 + @I) = 'Q'
                                     AND @Q = 1 )
                           AND NOT ( @Q = 0
                                     AND CHAR(64 + @I) = 'J' )
                          BEGIN
                              SET @NEXTLETTER = CHAR(64 + @I)
                              SET @USEDLETTERS = @USEDLETTERS + CHAR(64 + @I)
                              SET @I = @I + 1

                              BREAK
                          END

                        SET @I = @I + 1
                    END

                  -- SELECT 1 AS [T]
                  --BREAK
                  INSERT INTO @T_TABLE
                  SELECT @NEXTLETTER,
                         @COUNTER,
                         @COUNTER_2

                  SET @COUNTER = @COUNTER + 1
              END
        END

      SET @COUNTER_2 = @COUNTER_2 + 1
      SET @COUNTER = 1
  END

--Split word into Digraphs
WHILE @A < 1
  BEGIN
      SET @TESTWORDS = UPPER(LEFT(@INPUT, 2))

      IF LEN(@TESTWORDS) = 1
        BEGIN
            SET @TESTWORDS = @TESTWORDS + 'X'
            SET @A = 1
        END
      ELSE IF RIGHT(@TESTWORDS, 1) = LEFT(@TESTWORDS, 1)
        BEGIN
            SET @TESTWORDS = RIGHT(@TESTWORDS, 1) + 'X'
            SET @INPUT = RIGHT(@INPUT, LEN(@INPUT) - 1)
        END
      ELSE
        SET @INPUT = RIGHT(@INPUT, LEN(@INPUT) - 2)

      IF LEN(@INPUT) = 0
        SET @A = 1

      INSERT @WORDS
      SELECT @TESTWORDS,
             ''
  END

--Start Encryption
IF @ENCRYPT = 1
  BEGIN
      --Loop through Digraphs amd encrypt
      DECLARE WORDS_LOOP CURSOR LOCAL FORWARD_ONLY FOR
        SELECT WORD_PRE
        FROM   @WORDS
        FOR UPDATE OF WORD_POST

      OPEN WORDS_LOOP

      FETCH NEXT FROM WORDS_LOOP INTO @WORD

      WHILE @@FETCH_STATUS = 0
        BEGIN
            --Find letter positions
            SET @ROW1 = (SELECT ROWID
                         FROM   @T_TABLE
                         WHERE  LETTER = LEFT(@WORD, 1))
            SET @ROW2 = (SELECT ROWID
                         FROM   @T_TABLE
                         WHERE  LETTER = RIGHT(@WORD, 1))
            SET @COL1 = (SELECT COLID
                         FROM   @T_TABLE
                         WHERE  LETTER = LEFT(@WORD, 1))
            SET @COL2 = (SELECT COLID
                         FROM   @T_TABLE
                         WHERE  LETTER = RIGHT(@WORD, 1))

            --Move positions according to encryption rules
            IF @COL1 = @COL2
              BEGIN
                  SET @ROW1 = @ROW1 + 1
                  SET @ROW2 = @ROW2 + 1
              --select 'row'
              END
            ELSE IF @ROW1 = @ROW2
              BEGIN
                  SET @COL1 = @COL1 + 1
                  SET @COL2 = @COL2 + 1
              --select 'col'
              END
            ELSE
              BEGIN
                  SET @TMP = @COL2
                  SET @COL2 = @COL1
                  SET @COL1 = @TMP
              --select 'reg'
              END

            IF @ROW1 = 6
              SET @ROW1 = 1

            IF @ROW2 = 6
              SET @ROW2 = 1

            IF @COL1 = 6
              SET @COL1 = 1

            IF @COL2 = 6
              SET @COL2 = 1

            --Find encrypted letters by positions
            UPDATE @WORDS
            SET    WORD_POST = (SELECT (SELECT LETTER
                                        FROM   @T_TABLE
                                        WHERE  ROWID = @ROW1
                                               AND COLID = @COL1)
                                       + (SELECT LETTER
                                          FROM   @T_TABLE
                                          WHERE  COLID = @COL2
                                                 AND ROWID = @ROW2))
            WHERE  WORD_PRE = @WORD

            FETCH NEXT FROM WORDS_LOOP INTO @WORD
        END

      CLOSE WORDS_LOOP

      DEALLOCATE WORDS_LOOP
  END
--Start Decryption
ELSE
  BEGIN
      --Loop through Digraphs amd decrypt
      DECLARE WORDS_LOOP CURSOR LOCAL FORWARD_ONLY FOR
        SELECT WORD_PRE
        FROM   @WORDS
        FOR UPDATE OF WORD_POST

      OPEN WORDS_LOOP

      FETCH NEXT FROM WORDS_LOOP INTO @WORD

      WHILE @@FETCH_STATUS = 0
        BEGIN
            --Find letter positions
            SET @ROW1 = (SELECT ROWID
                         FROM   @T_TABLE
                         WHERE  LETTER = LEFT(@WORD, 1))
            SET @ROW2 = (SELECT ROWID
                         FROM   @T_TABLE
                         WHERE  LETTER = RIGHT(@WORD, 1))
            SET @COL1 = (SELECT COLID
                         FROM   @T_TABLE
                         WHERE  LETTER = LEFT(@WORD, 1))
            SET @COL2 = (SELECT COLID
                         FROM   @T_TABLE
                         WHERE  LETTER = RIGHT(@WORD, 1))

            --Move positions according to encryption rules
            IF @COL1 = @COL2
              BEGIN
                  SET @ROW1 = @ROW1 - 1
                  SET @ROW2 = @ROW2 - 1
              --select 'row'
              END
            ELSE IF @ROW1 = @ROW2
              BEGIN
                  SET @COL1 = @COL1 - 1
                  SET @COL2 = @COL2 - 1
              --select 'col'
              END
            ELSE
              BEGIN
                  SET @TMP = @COL2
                  SET @COL2 = @COL1
                  SET @COL1 = @TMP
              --select 'reg'
              END

            IF @ROW1 = 0
              SET @ROW1 = 5

            IF @ROW2 = 0
              SET @ROW2 = 5

            IF @COL1 = 0
              SET @COL1 = 5

            IF @COL2 = 0
              SET @COL2 = 5

            --Find decrypted letters by positions
            UPDATE @WORDS
            SET    WORD_POST = (SELECT (SELECT LETTER
                                        FROM   @T_TABLE
                                        WHERE  ROWID = @ROW1
                                               AND COLID = @COL1)
                                       + (SELECT LETTER
                                          FROM   @T_TABLE
                                          WHERE  COLID = @COL2
                                                 AND ROWID = @ROW2))
            WHERE  WORD_PRE = @WORD

            FETCH NEXT FROM WORDS_LOOP INTO @WORD
        END

      CLOSE WORDS_LOOP

      DEALLOCATE WORDS_LOOP
  END

--Output
DECLARE WORDS CURSOR LOCAL FAST_FORWARD FOR
  SELECT WORD_POST
  FROM   @WORDS

OPEN WORDS

FETCH NEXT FROM WORDS INTO @WORD

WHILE @@FETCH_STATUS = 0
  BEGIN
      SET @SQL = @SQL + @WORD + ' '

      FETCH NEXT FROM WORDS INTO @WORD
  END

CLOSE WORDS

DEALLOCATE WORDS

SELECT @SQL

--Cleanup
IF EXISTS (SELECT *
           FROM   SYS.TYPES
           WHERE  NAME = 'FairPlayTable')
  DROP TYPE FAIRPLAYTABLE

Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.


Works with: Oracle
-- set of numbers is a table
-- create one set with 3 elements

create table myset1 (element number);

insert into myset1 values (1);
insert into myset1 values (2);
insert into myset1 values (3);

commit;

-- check if 1 is an element

select 'TRUE' BOOL from dual
where 1 in
(select element from myset1);

-- create second set with 3 elements

create table myset2 (element number);

insert into myset2 values (1);
insert into myset2 values (5);
insert into myset2 values (6);

commit;

-- union sets

select element from myset1
union
select element from myset2;

-- intersection

select element from myset1
intersect
select element from myset2;

-- difference

select element from myset1
minus
select element from myset2;

-- subset

-- change myset2 to only have 1 as element

delete from myset2 where not element = 1;

commit;

-- check if myset2 subset of myset1

select 'TRUE' BOOL from dual
where 0 =  (select count(*) from
(select element from myset2
minus
select element from myset1));

-- equality

-- change myset1 to only have 1 as element

delete from myset1 where not element = 1;

commit;

 -- check if myset2 subset of myset1 and
 -- check if myset1 subset of myset2 and

select 'TRUE' BOOL from dual
where
0 =  (select count(*) from
(select element from myset2
minus
select element from myset1)) and
0 =
(select count(*) from
(select element from myset1
minus
select element from myset2));

SQL>
SQL> -- set of numbers is a table
SQL> -- create one set with 3 elements
SQL>
SQL> create table myset1 (element number);

Table created.

SQL>
SQL> insert into myset1 values (1);

1 row created.

SQL> insert into myset1 values (2);

1 row created.

SQL> insert into myset1 values (3);

1 row created.

SQL>
SQL> commit;

Commit complete.

SQL>
SQL> -- check if 1 is an element
SQL>
SQL> select 'TRUE' BOOL from dual
  2  where 1 in
  3  (select element from myset1);

BOOL
----
TRUE

SQL>
SQL> -- create second set with 3 elements
SQL>
SQL> create table myset2 (element number);

Table created.

SQL>
SQL> insert into myset2 values (1);

1 row created.

SQL> insert into myset2 values (5);

1 row created.

SQL> insert into myset2 values (6);

1 row created.

SQL>
SQL> commit;

Commit complete.

SQL>
SQL> -- union sets
SQL>
SQL> select element from myset1
  2  union
  3  select element from myset2;

   ELEMENT
----------
         1
         2
         3
         5
         6

SQL>
SQL> -- intersection
SQL>
SQL> select element from myset1
  2  intersect
  3  select element from myset2;

   ELEMENT
----------
         1

SQL>
SQL> -- difference
SQL>
SQL> select element from myset1
  2  minus
  3  select element from myset2;

   ELEMENT
----------
         2
         3

SQL>
SQL> -- subset
SQL>
SQL> -- change myset2 to only have 1 as element
SQL>
SQL> delete from myset2 where not element = 1;

2 rows deleted.

SQL>
SQL> commit;

Commit complete.

SQL>
SQL> -- check if myset2 subset of myset1
SQL>
SQL> select 'TRUE' BOOL from dual
  2  where 0 =  (select count(*) from
  3  (select element from myset2
  4  minus
  5  select element from myset1));

BOOL
----
TRUE

SQL>
SQL> -- equality
SQL>
SQL> -- change myset1 to only have 1 as element
SQL>
SQL> delete from myset1 where not element = 1;

2 rows deleted.

SQL>
SQL> commit;

Commit complete.

SQL>
SQL>  -- check if myset2 subset of myset1 and
SQL>  -- check if myset1 subset of myset2 and
SQL>
SQL> select 'TRUE' BOOL from dual
  2  where
  3  0 =  (select count(*) from
  4  (select element from myset2
  5  minus
  6  select element from myset1)) and
  7  0 =
  8  (select count(*) from
  9  (select element from myset1
 10  minus
 11  select element from myset2));

BOOL
----
TRUE

demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.


Oracle[edit]

select extract(year from dt) as year_with_xmas_on_sunday
from   (
         select  add_months(date '2008-12-25', 12 * (level - 1)) as dt
         from    dual
         connect by level <= 2121 - 2008 + 1
       )
where  to_char(dt, 'Dy', 'nls_date_language=English') = 'Sun'
order  by 1
;

determine the years between 2008 and 2121 when Christmas (25th December) falls on a Sunday. It uses standard date handling libraries of the programming language and compares the results with other languages to identify any anomalies due to issues like overflow in date/time representation. It also takes into account language settings in SQL and uses the TRUNC function to avoid complications related to these settings.


Works with: ORACLE 19c

/*
This code is an implementation of "Remove duplicate elements" in SQL ORACLE 19c
p_in_str    -- input string
p_delimiter -- delimeter
*/
with
  function remove_duplicate_elements(p_in_str in varchar2, p_delimiter in varchar2 default ',') return varchar2 is
  v_in_str varchar2(32767) := replace(p_in_str,p_delimiter,',');
  v_res    varchar2(32767);
begin
  --
  execute immediate 'select listagg(distinct cv,:p_delimiter) from (select (column_value).getstringval() cv from xmltable(:v_in_str))'
     into v_res using p_delimiter, v_in_str;
  --
  return v_res;
  --
end;

--Test
select remove_duplicate_elements('1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d"') as res from dual
union all
select remove_duplicate_elements('3 9 1 10 3 7 6 5 2 7 4 7 4 2 2 2 2 8 2 10 4 9 2 4 9 3 4 3 4 7',' ') as res from dual
;

"Implements a function to remove duplicate elements from an array using three possible methods: 1) Using a hash table, 2) Sorting the elements and removing consecutive duplicates, 3) Iterating through the list and discarding any repeated elements."


Works with: Oracle
select to_char(sysdate,'YYYY-MM-DD') date_fmt_1 from dual;

select to_char(sysdate,'fmDay, Month DD, YYYY') date_fmt_2 from dual;
SQL>
DATE_FMT_1
----------
2016-12-12

SQL> SQL>
DATE_FMT_2
--------------------------------------------------------------------------------
Monday, December 12, 2016

display the current date in two formats: "2007-11-23" and "Friday, November 23, 2007".


--
-- This only works under Oracle and has the limitation of 1 to 3999

SQL> select to_char(1666, 'RN') urcoman, to_char(1666, 'rn') lcroman from dual;

URCOMAN         LCROMAN
--------------- ---------------
        MDCLXVI         mdclxvi

create a function that converts a positive integer into its equivalent Roman numeral representation.


Works with: MS SQL version  2005
declare @s varchar(10)
set @s = 'alphaBETA'
print upper(@s)
print lower(@s)

demonstrate the conversion of the string "alphaBETA" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.


select translate(
        'The quick brown fox jumps over the lazy dog.',
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
        'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
        )
        from dual;
Works with: T-SQL
with cte(num) as
(
 select 1
 union all
 select num+1
 from cte
)
select cast((
select char(ascii(chr) +
		case
			when    ascii(chr) between ascii('a') and ascii('m') or
				ascii(chr) between ascii('A') and ascii('M') then 13
			when    ascii(chr) between ascii('n') and ascii('z') or
				ascii(chr) between ascii('N') and ascii('Z') then -13
			else    0
		end)
from
(
select top(1000) num,
		 -- your string to be converted to ROT13
                 substring('The Quick Brown Fox Jumps Over The Lazy Dog',num,1) chr
from cte
) tmp
For XML PATH ('')) as xml).value('.', 'VARCHAR(max)') rot13
option (maxrecursion 0)

implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is "rotated" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.


We can treat the array of data structures as a table. An order by clause in a query will sort the data.-- setup
create table pairs (name varchar(16), value varchar(16));
insert into pairs values ('Fluffy', 'cat');
insert into pairs values ('Fido', 'dog');
insert into pairs values ('Francis', 'fish');
-- order them by name
select * from pairs order by name;

sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.


REM Create a table to associate keys with values
CREATE TABLE  associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); .
REM Insert a Key Value Pair
INSERT (KEY_COLUMN, VALUE_COLUMN) VALUES ( 'VALUE','KEY');.
REM Retrieve a key value pair
SELECT aa.value_column FROM associative_array aa where aa.key_column = 'KEY';

"Create an associative array, also known as a dictionary, map, or hash."


select i, k, sum(A.N*B.N) as N
        from A inner join B on A.j=B.j
        group by i, k

implement a function to compute the dot product of two vectors of arbitrary length. The vectors need to be of the same length and the dot product is calculated by multiplying corresponding terms from each vector and summing the products. The code also includes a specification for calculating the inner product in SQL given two tables A and B with key columns i, j, and k, and value columns N.


select level card,
        to_char(to_date(level,'j'),'fmjth') ord
from dual
connect by level <= 15;

select to_char(to_date(5373485,'j'),'fmjth')
from dual;

      CARD ORD
---------- ------------------------------
         1 1st
         2 2nd
         3 3rd
         4 4th
         5 5th
         6 6th
         7 7th
         8 8th
         9 9th
        10 10th
        11 11th
        12 12th
        13 13th
        14 14th
        15 15th

15 rows selected.

select to_char(to_date(5373485,'j'),'fmjth')
                       *
ERROR at line 1:
ORA-01854: julian date must be between 1 and 5373484

The code is a function that takes an integer input greater than or equal to zero and returns a string of the number followed by an apostrophe and the corresponding ordinal suffix. The function is tested with the ranges 0..25, 250..265, and 1000..1025. The use of apostrophes in the output is optional.


Works with: ORACLE 19c

/*
This code is an implementation of "General FizzBuzz" in SQL ORACLE 19c
*/
select lpad( nvl(   case when mod(level, 3) = 0 then 'Fizz' end
                 || case when mod(level, 5) = 0 then 'Buzz' end
                 || case when mod(level, 7) = 0 then 'Baxx' end
                , level)
            ,12) as output
  from dual
connect by level <= 107
;
/

The code takes a maximum number and a list of factors with corresponding words as input from the user. It then prints numbers from 1 to the maximum number, replacing multiples of the given factors with their corresponding words. If a number is a multiple of multiple factors, it prints all associated words in the order of the factors.


-- drop tables
DROP TABLE IF EXISTS tmp_patients;
DROP TABLE IF EXISTS tmp_visits;

-- create tables
CREATE TABLE tmp_patients(
	PATIENT_ID INT,
	LASTNAME VARCHAR(20)
);

CREATE TABLE tmp_visits(
	PATIENT_ID INT,
	VISIT_DATE DATE,
	SCORE NUMERIC(4,1)
);

-- load data from csv files
/*
-- Note: LOAD DATA LOCAL requires `local-infile` enabled on both the client and server else you get error "#1148 command is not allowed.."
LOAD DATA LOCAL INFILE '/home/csv/patients.csv' INTO TABLE `tmp_patients` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES;
LOAD DATA LOCAL INFILE '/home/csv/visits.csv' INTO TABLE `tmp_visits` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES;
*/

-- load data hard coded
INSERT INTO tmp_patients(PATIENT_ID, LASTNAME)
VALUES
(1001, 'Hopper'),
(4004, 'Wirth'),
(3003, 'Kemeny'),
(2002, 'Gosling'),
(5005, 'Kurtz');

INSERT INTO tmp_visits(PATIENT_ID, VISIT_DATE, SCORE)
VALUES
(2002, '2020-09-10', 6.8),
(1001, '2020-09-17', 5.5),
(4004, '2020-09-24', 8.4),
(2002, '2020-10-08', NULL),
(1001, NULL, 6.6),
(3003, '2020-11-12', NULL),
(4004, '2020-11-05', 7.0),
(1001, '2020-11-19', 5.3);

-- join tables and group
SELECT
	p.PATIENT_ID,
	p.LASTNAME,
	MAX(VISIT_DATE) AS LAST_VISIT,
	SUM(SCORE) AS SCORE_SUM,
	CAST(AVG(SCORE) AS DECIMAL(10,2)) AS SCORE_AVG
FROM
	tmp_patients p
	LEFT JOIN tmp_visits v
		ON v.PATIENT_ID = p.PATIENT_ID
GROUP BY
	p.PATIENT_ID,
	p.LASTNAME
ORDER BY
	p.PATIENT_ID;

"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file."


The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is "ha" and 5, the output will be "hahahahaha". Similarly, if the input is "*" and 5, the output will be "*****".


Works with: Oracle
-- test.sql
-- Tested in SQL*plus

drop table test;

create table test (a integer, b integer);

insert into test values ('&&A','&&B');

commit;

select a-b difference from test;

select a*b product from test;

select trunc(a/b) integer_quotient from test;

select mod(a,b) remainder from test;

select power(a,b) exponentiation from test;
SQL> @test.sql

Table dropped.

Table created.

Enter value for a: 3
Enter value for b: 4
old   1: insert into test values ('&&A','&&B')
new   1: insert into test values ('3','4')

1 row created.

Commit complete.

DIFFERENCE
----------
        -1

   PRODUCT
----------
        12

INTEGER_QUOTIENT
----------------
               0

 REMAINDER
----------
         3

EXPONENTIATION
--------------
            81

take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.


Byte length[edit]

Character length[edit]

calculate the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. The codes handle Unicode code points correctly, distinguishing between character counts in code points and code unit counts. The codes also provide the string length in graphemes if the language supports it. The examples provided use the string "møøse" and "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" to demonstrate the functionality.


Works with: oracle version 11.2 and higher

with
  symbols (d) as (select to_char(level) from dual connect by level <=  9)
, board   (i) as (select level          from dual connect by level <= 81)
, neighbors (i, j) as (
    select b1.i, b2.i
    from   board b1 inner join board b2
      on   b1.i != b2.i
           and (
                    mod(b1.i - b2.i, 9) = 0
                 or ceil(b1.i /  9) = ceil(b2.i /  9)
                 or ceil(b1.i / 27) = ceil(b2.i / 27) and trunc(mod(b1.i - 1, 9) / 3) = trunc(mod(b2.i - 1, 9) / 3)
               )
  )
, r (str, pos) as (
    select  :game, instr(:game, ' ')
      from  dual
    union all
    select  substr(r.str, 1, r.pos - 1) || s.d || substr(r.str, r.pos + 1), instr(r.str, ' ', r.pos + 1)
      from  r inner join symbols s
        on  r.pos > 0 and not exists (
                                       select *
                                       from   neighbors n
                                       where  r.pos = n.i and s.d = substr(r.str, n.j, 1)
                                     )
  )
select str
from   r
where  pos = 0
;

implement a Sudoku solver that fills in a partially completed 9x9 grid and displays the result in a human-readable format. The solution uses a recursive WITH clause, supported by some SQL dialects, and was tested in Oracle SQL. It employs a brute force algorithm that can solve most problems in less than a second. The input and output are presented as strings of 81 characters, with each character representing a digit or a space for an empty cell. The solution can be optimized by creating a table NEIGHBORS and an index on column I of that table.


The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


drop table tbl;
create table tbl
(
        u       number,
        v       number
);

insert into tbl ( u, v ) values ( 20, 50 );
insert into tbl ( u, v ) values ( 21, 50 );
insert into tbl ( u, v ) values ( 21, 51 );
insert into tbl ( u, v ) values ( 22, 50 );
insert into tbl ( u, v ) values ( 22, 55 );

commit;

with
        function gcd ( ui in number, vi in number )
        return number
        is
                u number := ui;
                v number := vi;
                t number;
        begin
                while v > 0
                loop
                        t := u;
                        u := v;
                        v:= mod(t, v );
                end loop;
                return abs(u);
        end gcd;
        select u, v, gcd ( u, v )
        from tbl
/

find the greatest common divisor (GCD) or greatest common factor (GCF) of two integers. This is related to the task of finding the least common multiple. The code also includes demonstrations of Oracle 12c WITH Clause Enhancements, SQL Server 2008, and a PostgreSQL function using a recursive common table expression.


Works with: MS SQL version Server 2005
declare @s varchar(10)
set @s = '1234.56'

print isnumeric(@s) --prints 1 if numeric, 0 if not.

if isnumeric(@s)=1 begin print 'Numeric' end
else print 'Non-numeric'

"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax."


Library: SQL
Oracle SQL[edit]
SELECT CASE
    WHEN MOD(level,15)=0 THEN 'FizzBuzz'
    WHEN MOD(level,3)=0 THEN 'Fizz'
    WHEN MOD(level,5)=0 THEN 'Buzz'
    ELSE TO_CHAR(level)
    END FizzBuzz
    FROM dual
    CONNECT BY LEVEL <= 100;

SELECT nvl(decode(MOD(level,3),0,'Fizz')||decode(MOD(level,5),0,'Buzz'),level)
FROM dual
CONNECT BY level<=100;
PostgreSQL specific[edit]
SELECT i, fizzbuzz
  FROM
    (SELECT i,
            CASE
              WHEN i % 15 = 0 THEN 'FizzBuzz'
              WHEN i %  5 = 0 THEN 'Buzz'
              WHEN i %  3 = 0 THEN 'Fizz'
              ELSE NULL
            END AS fizzbuzz
       FROM generate_series(1,100) AS i) AS fb
 WHERE fizzbuzz IS NOT NULL;

SELECT COALESCE(FIZZ || BUZZ, FIZZ, BUZZ, OUTPUT) AS FIZZBUZZ FROM
(SELECT GENERATE_SERIES AS FULL_SERIES, TO_CHAR(GENERATE_SERIES,'99') AS OUTPUT
FROM GENERATE_SERIES(1,100)) F LEFT JOIN
(SELECT TEXT 'Fizz' AS FIZZ, GENERATE_SERIES AS FIZZ_SERIES FROM GENERATE_SERIES(0,100,3)) FIZZ ON
FIZZ.FIZZ_SERIES = F.FULL_SERIES LEFT JOIN
(SELECT TEXT 'Buzz' AS BUZZ, GENERATE_SERIES AS BUZZ_SERIES FROM GENERATE_SERIES(0,100,5)) BUZZ ON
BUZZ.BUZZ_SERIES = F.FULL_SERIES;
Recursive Common Table Expressions (MSSQL 2005+)[edit]
WITH nums (n, fizzbuzz ) AS (
	SELECT 1, CONVERT(nvarchar, 1) UNION ALL
	SELECT
		(n + 1) as n1,
		CASE
			WHEN (n + 1) % 15 = 0 THEN 'FizzBuzz'
			WHEN (n + 1) % 3  = 0 THEN 'Fizz'
			WHEN (n + 1) % 5  = 0 THEN 'Buzz'
			ELSE CONVERT(nvarchar, (n + 1))
		END
	FROM nums WHERE n < 100
)
SELECT n, fizzbuzz FROM nums
ORDER BY n ASC
OPTION ( MAXRECURSION 100 )
SQL Anywhere specific - minimalist[edit]
SELECT
        isnull(if row_num % 3 = 0 then 'Fizz' endif + if row_num % 5 = 0 then 'Buzz' endif, str(row_num))
FROM
        sa_rowgenerator(1,100)
Generic SQL using a join[edit]

-- Load some numbers
CREATE TABLE numbers(i INTEGER);
INSERT INTO numbers VALUES(1);
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
-- Define the fizzes and buzzes
CREATE TABLE fizzbuzz (message VARCHAR(8), divisor INTEGER);
INSERT INTO fizzbuzz VALUES('fizz',      3);
INSERT INTO fizzbuzz VALUES('buzz',      5);
INSERT INTO fizzbuzz VALUES('fizzbuzz', 15);
-- Play fizzbuzz
SELECT COALESCE(max(message),CAST(i AS VARCHAR(99))) as result
FROM numbers LEFT OUTER JOIN fizzbuzz ON MOD(i,divisor) = 0
GROUP BY i
HAVING i <= 100
ORDER BY i;
-- Tidy up
DROP TABLE fizzbuzz;
DROP TABLE numbers;

The code prints integers from 1 to 100. For multiples of three, it prints 'Fizz' instead of the number. For multiples of five, it prints 'Buzz' instead of the number. For numbers that are multiples of both three and five, it prints 'FizzBuzz'. This is a solution to the FizzBuzz problem.


Works with: Oracle
select host_name from v$instance;

"Determines and outputs the hostname of the current system where the routine is running."


Works with: PL/pgSQL

RLE encoding
-- variable table
drop table if exists var;
create temp table var (	value varchar(1000) );
insert into var(value) select 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW';

-- select
with recursive
ints(num) as
(
	select 1
	union all
	select num+1
	from ints
	where num+1 <= length((select value from var))
)
,
chars(num,chr,nextChr,isGroupEnd) as
(
	select tmp.*, case when tmp.nextChr <> tmp.chr then 1 else 0 end groupEnds
	from (
	select num,
		   substring((select value from var), num, 1) chr,
		   (select substring((select value from var), num+1, 1)) nextChr
	from ints
	) tmp
)
select (select value from var) plain_text, (
	select string_agg(concat(cast(maxNoWithinGroup as varchar(10)) , chr), '' order by num)
	from (
		select *, max(noWithinGroup) over (partition by chr, groupNo) maxNoWithinGroup
		from (
			select	num,
					chr,
					groupNo,
					row_number() over( partition by chr, groupNo order by num) noWithinGroup
			from (
			select *, (select count(*)
					   from chars chars2
					   where chars2.isGroupEnd = 1 and
					   chars2.chr = chars.chr and
					   chars2.num < chars.num) groupNo
			from chars
			) tmp
		) sub
	) final
	where noWithinGroup = 1
	) Rle_Compressed
RLE decoding
-- variable table
DROP TABLE IF EXISTS var;
CREATE temp TABLE var (	VALUE VARCHAR(1000) );
INSERT INTO var(VALUE) SELECT '1A2B3C4D5E6F';

-- select
WITH recursive
ints(num) AS
(
	SELECT 1
	UNION ALL
	SELECT num+1
	FROM ints
	WHERE num+1 <= LENGTH((SELECT VALUE FROM var))
)
,
chars(num,chr,nextChr) AS
(
	SELECT tmp.*
	FROM (
	SELECT num,
		SUBSTRING((SELECT VALUE FROM var), num, 1) chr,
		(SELECT SUBSTRING((SELECT VALUE FROM var), num+1, 1)) nextChr
	FROM ints
	) tmp
)
,
charsWithGroup(num,chr,nextChr,group_no) AS
(
	SELECT *,(SELECT COUNT(*)
		FROM chars chars2
		WHERE chars2.chr !~ '[0-9]' AND
		chars2.num < chars.num) group_No
	FROM chars
)
,
charsWithGroupAndLetter(num,chr,nextChr,group_no,group_letter) AS
(
	SELECT *,(SELECT chr
		FROM charsWithGroup g2
		where g2.group_no = charsWithGroup.group_no
		ORDER BY num DESC
		LIMIT 1)
	FROM charsWithGroup
)
,
lettersWithCount(group_no,amount,group_letter) AS
(
	SELECT group_no, string_agg(chr, '' ORDER BY num), group_letter
	FROM charsWithGroupAndLetter
	WHERE chr ~ '[0-9]'
	GROUP BY group_no, group_letter
)
,
lettersReplicated(group_no,amount,group_letter, replicated_Letter) AS
(
	SELECT *, rpad(group_letter, cast(amount as int), group_letter)
	FROM lettersWithCount
)
select (SELECT value FROM var) rle_encoded,
	string_agg(replicated_Letter, '' ORDER BY group_no) decoded_string
FROM lettersReplicated

implement a run-length encoding algorithm that compresses a string of uppercase characters by storing the length of consecutive runs of the same character. It also provides a function to reverse the compression.


WITH RECURSIVE
  positions(i) as (
    VALUES(0)
    UNION SELECT ALL
    i+1 FROM positions WHERE i < 63
    ),
  solutions(board, n_queens) AS (
    SELECT '----------------------------------------------------------------', cast(0 AS bigint)
      FROM positions
    UNION
    SELECT
      substr(board, 1, i) || '*' || substr(board, i+2),n_queens + 1 as n_queens
      FROM positions AS ps, solutions
    WHERE n_queens < 8
      AND substr(board,1,i) != '*'
      AND NOT EXISTS (
        SELECT 1 FROM positions WHERE
          substr(board,i+1,1) = '*' AND
            (
                i % 8 = ps.i %8 OR
                cast(i / 8 AS INT) = cast(ps.i / 8 AS INT) OR
                cast(i / 8 AS INT) + (i % 8) = cast(ps.i / 8 AS INT) + (ps.i % 8) OR
                cast(i / 8 AS INT) - (i % 8) = cast(ps.i / 8 AS INT) - (ps.i % 8)
            )
        LIMIT 1
        )
   ORDER BY n_queens DESC -- remove this when using Postgres (they don't support ORDER BY in CTEs)
  )
SELECT board,n_queens FROM solutions WHERE n_queens = 8;

implement a solution to the N-queens problem, specifically for an 8x8 board, using Common Table Expressions. The solution has been tested with SQLite (>=3.8.3) and Postgres and may be compatible with other SQL dialects. The code and a Python script to run it are available on Github.


WITH KnapsackItems (item, [weight], value) AS
(
    SELECT 'map',9,  150
    UNION ALL SELECT 'compass',13,  35
    UNION ALL SELECT 'water',153,  200
    UNION ALL SELECT 'sandwich',50,  160
    UNION ALL SELECT 'glucose',15,  60
    UNION ALL SELECT 'tin',68,  45
    UNION ALL SELECT 'banana',27,  60
    UNION ALL SELECT 'apple',39,  40
    UNION ALL SELECT 'cheese',23,  30
    UNION ALL SELECT 'beer',52,  10
    UNION ALL SELECT 'suntan cream',11,  70
    UNION ALL SELECT 'camera',32,  30
    UNION ALL SELECT 'T-shirt',24,  15
    UNION ALL SELECT 'trousers',48,  10
    UNION ALL SELECT 'umbrella',73,  40
    UNION ALL SELECT 'waterproof trousers',42,  70
    UNION ALL SELECT 'waterproof overclothes',43,  75
    UNION ALL SELECT 'note-case',22,  80
    UNION ALL SELECT 'sunglasses',7,  20
    UNION ALL SELECT 'towel',18,  12
    UNION ALL SELECT 'socks',4,  50
    UNION ALL SELECT 'book',30,  10
)
SELECT *
INTO #KnapsackItems
FROM KnapsackItems;

WITH UNIQUEnTuples (n, Tuples, ID, [weight], value) AS (
    SELECT 1, CAST(item AS VARCHAR(8000)), item, [weight], value
    FROM #KnapsackItems
    UNION ALL
    SELECT 1 + n.n, t.item + ',' + n.Tuples, item, n.[weight] + t.[weight], n.value + t.value
    FROM UNIQUEnTuples n
    CROSS APPLY (
        SELECT item, [weight], value
        FROM #KnapsackItems t
        WHERE t.item < n.ID AND n.[weight] + t.[weight] < 400) t
    )
SELECT TOP 5 *
FROM UNIQUEnTuples
ORDER BY value DESC, n, Tuples;

GO
DROP TABLE #KnapsackItems;

Implement a solution for the 0-1 Knapsack problem where a tourist needs to maximize the total value of items he can carry in his knapsack without exceeding a weight limit of 4kg. The solution uses a recursive CTE and runs on SQL Server 2005 or later, displaying the top 5 optimal combinations of items.


Works with: MySQL
SELECT MD5('The quick brown fox jumped over the lazy dog\'s back')

implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5/Implementation for a scratch implementation.


SET @txt = REPLACE('In girum imus nocte et consumimur igni', ' ', '');
SELECT REVERSE(@txt) = @txt;

implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.


make "stack []
push "stack 1
push "stack 2
push "stack 3
print pop "stack   ; 3
print empty? :stack ; false

implement a stack with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and allows access to the topmost element without modifying the stack. It also includes features for testing if the stack is empty.


to fib :n [:a 0] [:b 1]
  if :n < 1 [output :a]
  output (fib :n-1 :b :a+:b)
end

generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.


to even? :n
  output equal? 0 modulo :n 2
end
show filter "even? [1 2 3 4]    ; [2 4]

show filter [equal? 0 modulo ? 2] [1 2 3 4]

select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.


Works with: UCB Logo

to items :n :thing
  if :n >= count :thing [output :thing]
  output items :n butlast :thing
end

to butitems :n :thing
  if or :n <= 0 empty? :thing [output :thing]
  output butitems :n-1 butfirst :thing
end

to middle :n :m :thing
  output items :m-(:n-1) butitems :n-1 :thing
end

to lastitems :n :thing
  if :n >= count :thing [output :thing]
 output lastitems :n butfirst :thing
end

to starts.with :sub :thing
  if empty? :sub [output "true]
  if empty? :thing [output "false]
  if not equal? first :sub first :thing [output "false]
  output starts.with butfirst :sub butfirst :thing
end

to members :sub :thing
  output cascade [starts.with :sub ?] [bf ?] :thing
end

; note: Logo indices start at one
make "s "abcdefgh
print items 3 butitems 2 :s ; cde
print middle 3 5  :s   ; cde
print butitems 2  :s   ; cdefgh
print butlast     :s   ; abcdefg
print items 3 member  "d  :s ; def
print items 3 members "de :s ; def

"Output: The code displays a substring from a string in various ways: starting from a specific character position and of a certain length, starting from a specific character position to the end of the string, excluding the last character of the string, starting from a known character within the string of a certain length, and starting from a known substring within the string of a certain length. The code works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not 8-bit or 16-bit code units. It is not designed to handle all Unicode characters for other encodings like 8-bit ASCII or EUC-JP."


take a string as input, reverse it, and return the reversed string. It also ensures the preservation of Unicode combining characters. It can handle both words and lists.


; Determine if a Gregorian calendar year is leap
to leap? :year
  output (and
    equal? 0 modulo :year 4
    not member? modulo :year 400 [100 200 300]
  )
end

; Convert Gregorian calendar date to a simple day count from
; day 1 = January 1, 1 CE
to day_number :year :month :day
  local "elapsed make "elapsed difference :year 1
  output (sum  product 365 :elapsed
              int quotient :elapsed 4
              minus int quotient :elapsed 100
              int quotient :elapsed 400
              int quotient difference product 367 :month 362 12
              ifelse lessequal? :month 2 0 ifelse leap? :year -1 -2
              :day)
end

; Find the day of the week from a day number; 0 = Sunday through 6 = Saturday
to day_of_week :day_number
  output modulo :day_number 7
end

; True if the given day is a Sunday
to sunday? :year :month :day
  output equal? 0 day_of_week day_number :year :month :day
end

; Put it all together to answer the question posed in the problem
print filter [sunday? ? 12 25] iseq 2008 2121
bye

The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date/time representation, such as overflow issues similar to y2k problems.


Works with: UCB Logo
show remdup [1 2 3 a b c 2 3 4 b c d]   ; [1 a 2 3 4 b c d]

implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.


; quicksort (lists, functional)

to small? :list
  output or [empty? :list] [empty? butfirst :list]
end
to quicksort :list
  if small? :list [output :list]
  localmake "pivot first :list
  output (sentence
    quicksort filter [? < :pivot] butfirst :list
              filter [? = :pivot]          :list
    quicksort filter [? > :pivot] butfirst :list
  )
end

show quicksort [1 3 5 7 9 8 6 4 2]
; quicksort (arrays, in-place)

to incr :name
  make :name (thing :name) + 1
end
to decr :name
  make :name (thing :name) - 1
end
to swap :i :j :a
  localmake "t item :i :a
  setitem :i :a item :j :a
  setitem :j :a :t
end

to quick :a :low :high
  if :high <= :low [stop]
  localmake "l :low
  localmake "h :high
  localmake "pivot item ashift (:l + :h) -1  :a
  do.while [
    while [(item :l :a) < :pivot] [incr "l]
    while [(item :h :a) > :pivot] [decr "h]
    if :l <= :h [swap :l :h :a  incr "l  decr "h]
  ] [:l <= :h]
  quick :a :low :h
  quick :a :l :high
end
to sort :a
  quick :a first :a count :a
end

make "test {1 3 5 7 9 8 6 4 2}
sort :test
show :test

implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.


Works with: UCB Logo

print first shell [date +%F]
print first shell [date +"%A, %B %d, %Y"]

display the current date in two different formats: "2007-11-23" and "Friday, November 23, 2007". It uses UCB Logo to call out to the shell due to the absence of standard built-in time and date functions in Logo.


to powerset :set
  if empty? :set [output [[]]]
  localmake "rest powerset butfirst :set
  output sentence  map [sentence first :set ?] :rest  :rest
end

show powerset [1 2 3]
[[1 2 3] [1 2] [1 3] [1] [2 3] [2] [3] []]

implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.


make "roman.rules [
  [1000 M] [900 CM] [500 D] [400 CD]
  [ 100 C] [ 90 XC] [ 50 L] [ 40 XL]
  [  10 X] [  9 IX] [  5 V] [  4 IV]
  [   1 I]
]

to roman :n [:rules :roman.rules] [:acc "||]
  if empty? :rules [output :acc]
  if :n < first first :rules [output (roman :n bf :rules :acc)]
  output (roman :n - first first :rules  :rules  word :acc last first :rules)
end
Works with: UCB Logo
make "patterns [[?] [? ?] [? ? ?] [? ?2] [?2] [?2 ?] [?2 ? ?] [?2 ? ? ?] [? ?3]]

to digit :d :numerals
  if :d = 0 [output "||]
  output apply (sentence "\( "word (item :d :patterns) "\)) :numerals
end
to digits :n :numerals
  output word ifelse :n < 10 ["||] [digits int :n/10 bf bf :numerals] ~
              digit modulo :n 10 :numerals
end
to roman :n
  if or :n < 0 :n >= 4000 [output [EX MODVS!]]
  output digits :n [I V X L C D M]
end

print roman 1999  ; MCMXCIX
print roman 25    ; XXV
print roman 944   ; CMXLIV

create a function that converts a positive integer into its equivalent Roman numeral representation.


array 5      ; default origin is 1, every item is empty
(array 5 0)  ; custom origin
make "a {1 2 3 4 5}  ; array literal
setitem 1 :a "ten       ; Logo is dynamic; arrays can contain different types
print item 1 :a   ; ten

demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and includes the functionality of pushing a value into the array.


Works with: UCB Logo
to copy :from :to
  openread :from
  openwrite :to
  setread :from
  setwrite :to
  until [eof?] [print readrawline]
  closeall
end

copy "input.txt "output.txt

demonstrate reading the contents of "input.txt" file into a variable and then writing this variable's contents into a new file called "output.txt".


print uppercase "alphaBETA  ; ALPHABETA
print lowercase "alphaBETA  ; alphabeta

demonstrate the conversion of the string "alphaBETA" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.


members of a list: [one two three]
items in an array: {one two three}
characters in a word: "123

create a collection in a statically-typed language, add values to it, and review the programming examples for compliance with the task requirements. The code also involves the use of different data types and collection abstractions such as arrays, associative arrays, compound data types, linked lists, queues, sets, stacks, and list-like protocols in Logo.


to comma.list :n
  repeat :n-1 [type repcount type "|, |]
  print :n
end

comma.list 10

The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.


to starts.with? :sub :thing
  if empty? :sub [output "true]
  if empty? :thing [output "false]
  if not equal? first :sub first :thing [output "false]
  output starts.with? butfirst :sub butfirst :thing
end

to ends.with? :sub :thing
  if empty? :sub [output "true]
  if empty? :thing [output "false]
  if not equal? last :sub last :thing [output "false]
  output ends.with? butlast :sub butlast :thing
end

show starts.with? "dog "doghouse    ; true
show ends.with? "house "doghouse    ; true
show substring? "gho "doghouse       ; true  (built-in)

The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.


fput item list ; add item to the head of a list

first list  ; get the data
butfirst list ; get the remainder
bf list       ; contraction for "butfirst"

.setfirst list value
.setbf list remainder

define a data structure for a singly-linked list element. This element holds a numeric value and a mutable link to the next element.


to tree :depth :length :scale :angle
  if :depth=0 [stop]
  setpensize round :depth/2
  forward :length
  right :angle
  tree :depth-1 :length*:scale :scale :angle
  left 2*:angle
  tree :depth-1 :length*:scale :scale :angle
  right :angle
  back :length
end

clearscreen
tree 10 80 0.7 30

generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.


to factors :n
  output filter [equal? 0 modulo :n ?] iseq 1 :n
end

show factors 28       ; [1 2 4 7 14 28]

compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.


Works with: MSWlogo

to cuboid :l1 :l2 :l3
cs perspective ;making the room ready to use
setxyz :l1   0    0
setxyz :l1 :l2    0
setxyz   0 :l2    0
setxyz   0   0    0
setxyz :l1   0    0
setxyz :l1   0 -:l3
setxyz :l1 :l2 -:l3
setxyz :l1 :l2    0
setxyz   0 :l2    0
setxyz   0 :l2 -:l3
setxyz :l1 :l2 -:l3
end

cuboid 50 100 150

"Generates a graphical or ASCII art representation of a 2x3x4 cuboid, with three visible faces, using either static or rotational projection. Implemented in Logo using the perspective function for easier 3D object drawing."


to rot13 :c
  make "a difference ascii lowercase :c  ascii "a
  if or :a < 0 :a > 25 [output :c]
  make "delta ifelse :a < 13 [13] [-13]
  output char sum :delta ascii :c
end

print map "rot13 "|abjurer NOWHERE|
nowhere ABJURER

implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is "rotated" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.


for [i 1 5] [repeat :i [type "*] (print)]
repeat 5 [repeat repcount [type "*] (print)]

demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.


pprop "animals "cat 5
pprop "animals "dog 4
pprop "animals "mouse 11
print gprop "animals "cat    ; 5
remprop "animals "dog
show plist "animals    ;  [mouse 11 cat 5]

"Creates an associative array, dictionary, map, or hash using UCB Logo's property lists to associate names with values."


; Configuration parameters for Microsoft and BSD implementations
make "LCG_MS [214013 2531011 65536 2147483648]
make "LCG_BSD [1103515245 12345 1 2147483648]

; Default seed is 0
make "_lcg_value 0

; set the seed
to lcg_seed :seed
  make "_lcg_value :seed
end

; generate the next number in the series using the given parameters
to lcg_rand [:config :LCG_MS]
  local "a local "c local "d local "m
  foreach [a c d m] [
    make ? item # :config
  ]
  make "_lcg_value (modulo (sum (product :a :_lcg_value) :c) :m)
  output int quotient :_lcg_value :d
end

foreach (list :LCG_BSD :LCG_MS) [
  lcg_seed 0
  repeat 10 [
    print (lcg_rand ?)
  ]
  print []
]
bye

The code replicates two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). It uses the Linear Congruential Generator (LCG) formula to generate a sequence of random numbers, starting from a seed value. The generated sequence should match the original generator's sequence when started from the same seed. The BSD formula generates random numbers in the range of 0 to 2147483647, while the Microsoft formula generates random numbers in the range of 0 to 32767.


to insert :after :list :value
  localmake "tail member :after :list
  if not empty? :tail [.setbf :tail fput :value bf :tail]
  output :list
end

show insert 5 [3 5 1 8] 2
[3 5 2 1 8]

"Defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element C into a list of elements A->B, after element A."


to double :x
  output ashift :x  1
end
to halve :x
  output ashift :x -1
end
to even? :x
  output equal? 0 bitand 1 :x
end
to eproduct :x :y
  if :x = 0 [output 0]
  ifelse even? :x ~
    [output      eproduct halve :x double :y] ~
    [output :y + eproduct halve :x double :y]
end

The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.


Recursive[edit]
to factorial :n
  if :n < 2 [output 1]
  output :n * factorial :n-1
end
Iterative[edit]

to factorial :n
	make "fact 1
	make "i 1
	repeat :n [make "fact :fact * :i make "i :i + 1]
	print :fact
end

The code implements a function to calculate the factorial of a positive integer number. The factorial is the product of all positive integers from the input number down to one. The function can be either iterative or recursive. It optionally handles errors for negative input numbers. The code may require slight modifications to run on different Logo implementations.


Works with: UCB Logo
to ok? :n
  output (and [number? :n] [4 = count :n] [4 = count remdup :n] [not member? 0 :n])
end

to init
  do.until [make "hidden random 10000] [ok? :hidden]
end

to guess :n
  if not ok? :n [print [Bad guess! (4 unique digits, 1-9)]  stop]
  localmake "bulls 0
  localmake "cows  0
  foreach :n [cond [
    [[? = item # :hidden] make "bulls 1 + :bulls]
    [[member?  ? :hidden] make "cows  1 + :cows ]
  ]]
  (print :bulls "bulls, :cows "cows)
  if :bulls = 4 [print [You guessed it!]]
end

generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.


Works with: UCB Logo

to random.float   ; 0..1
  localmake "max.int lshift -1 -1
  output quotient random :max.int :max.int
end

to random.gaussian
  output product cos random 360  sqrt -2 / ln random.float
end

make "randoms cascade 1000 [fput random.gaussian / 2 + 1 ?] []

generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using a built-in floating point random generator or an algorithm for uniformly distributed random numbers.


to dotprod :a :b
  output apply "sum (map "product :a :b)
end

show dotprod [1 3 -5] [4 -2 -1]    ; 3

Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].


readline - returns a line as a list of words
readword - returns a line as a single word, or an empty list if it reached the end of file
readrawline - returns a line as a single word, with no characters escaped
while [not eof?] [print readline]

continuously read data from a text stream either word-by-word or line-by-line until there is no more data available.


Works with: UCB Logo
Other Logo variants might have a built-in command, but UCB Logo must access the Unix shell to get time.to time
  output first first shell [date +%s]
end

make "start time
wait 300              ; 60ths of a second
print time - :start   ; 5

the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.


Works with: MSWlogo
to sphere :r
cs perspective ht ;making the room ready to use
repeat 180 [polystart circle :r polyend down 1]
polyview
end

represent the functionality of drawing a sphere, either graphically or in ASCII art, with the option of static or rotational projection. The drawing process is simplified in logo using the perspective function.


to strip :string :chars
  output filter [not substringp ? :chars] :string
end

print strip "She\ was\ a\ soul\ stripper.\ She\ took\ my\ heart! "aei

bye

"Function to remove specific characters from a given string"


Recursive[edit]
to dcr :step :length
  make "step :step - 1
  make "length :length / 1.41421
  if :step > 0 [rt 45 dcr :step :length lt 90 dcl :step :length rt 45]
  if :step = 0 [rt 45 fd :length lt 90 fd :length rt 45]
end

to dcl :step :length
  make "step :step - 1
  make "length :length / 1.41421
  if :step > 0 [lt 45 dcr :step :length rt 90 dcl :step :length lt 45]
  if :step = 0 [lt 45 fd :length rt 90 fd :length lt 45]
end

to dc :step :length :dir
  if :step = 0 [fd :length stop]
  rt :dir
  dc :step-1 :length/1.41421  45
  lt :dir lt :dir
  dc :step-1 :length/1.41421 -45
  rt :dir
end
to dragon :step :length
  dc :step :length 45
end

to O :step :length
  if :step=1 [Rt 90 fd :length Lt 90] [O (:step - 1) (:length / 1.41421) N (:step - 1) (:length / 1.41421)]
end

to N :step :length
  if :step=1 [fd :length] [W (:step - 1) (:length / 1.41421) N (:step - 1) (:length / 1.41421)]
end

to W :step :length
  if :step=1 [Lt 90 fd :length Rt 90] [W (:step - 1) (:length / 1.41421) S (:step - 1) (:length / 1.41421)]
end

to S :step :length
  if :step=1 [Rt 180 fd :length Lt 180] [O (:step - 1) (:length / 1.41421) S (:step - 1) (:length / 1.41421)]
end
Iterative[edit]

Works with: UCB Logo
; Return the bit above the lowest 1-bit in :n.
; If :n = binary "...z100..00" then the return is "z000..00".
; Eg. n=22 is binary 10110 the lowest 1-bit is the "...1." and the return is
; bit above that "..1.," which is 4.
to bit.above.lowest.1bit :n
  output bitand :n (1 + (bitxor :n (:n - 1)))
end

; Return angle +90 or -90 for dragon curve turn at point :n.
; The curve is reckoned as starting from n=0 so the first turn is at n=1.
to dragon.turn.angle :n
  output ifelse (bit.above.lowest.1bit :n) = 0  [90] [-90]
end

; Draw :steps many segments of the dragon curve.
to dragon :steps
  localmake "step.len 12  ; length of each step
  repeat :steps [
    forward :step.len
    left    dragon.turn.angle repcount  ; repcount = 1 to :steps inclusive
  ]
end

dragon 256
; Draw :steps many segments of the dragon curve, with corners chamfered
; off with little 45-degree diagonals.
; Done this way the vertices don't touch.
to dragon.chamfer :steps
  localmake "step.len       12  ; length of each step
  localmake "straight.frac  0.5 ; fraction of the step to go straight

  localmake "straight.len   :step.len * :straight.frac
  localmake "diagonal.len   (:step.len - :straight.len) * sqrt(1/2)

  repeat :steps [
     localmake "turn  (dragon.turn.angle repcount)/2   ; +45 or -45
     forward :straight.len
     left    :turn
     forward :diagonal.len
     left    :turn
  ]
end

dragon.chamfer 256

The code generates a dragon curve fractal, which can be displayed directly or written to an image file. It uses recursive and iterative methods, as well as successive approximation and Lindenmayer system of expansions. The dragon curve is constructed by following specific algorithms that determine the curl direction and the angle of the curve. The code also includes functions to calculate the absolute direction, X,Y coordinates of a point, and to test whether a given point or segment is on the curve. It can be started with parameters to determine the desired expansion level and curl direction.


show map "char iseq 97 122

show map "char apply "iseq map "ascii [a z]

generate an array, list, or string of all lowercase ASCII characters from 'a' to 'z'. The code should be written in a reliable style suitable for a large program and use strong typing if possible. It should avoid manually enumerating all the lowercase characters to prevent bugs. It should be straightforward and avoid using magic numbers.


to small? :list
  output or [empty? :list] [empty? bf :list]
end
to every.other :list
  if small? :list [output :list]
  output fput first :list every.other bf bf :list
end
to wordtolist :word
  output map.se [?] :word
end

to double.digit :digit
  output item :digit {0 2 4 6 8 1 3 5 7 9}@0
  ; output ifelse :digit < 5 [2*:digit] [1 + modulo 2*:digit 10]
end

to luhn :credit
  localmake "digits reverse filter [number? ?] wordtolist :credit
  localmake "s1 apply "sum every.other :digits
  localmake "s2 apply "sum map "double.digit every.other bf :digits
  output equal? 0 last sum :s1 :s2
end

show luhn "49927398716          ; true
show luhn "49927398717          ; false
show luhn "1234-5678-1234-5678  ; false
show luhn "1234-5678-1234-5670  ; true

The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.


to copies :n :thing [:acc "||]
  if :n = 0 [output :acc]
  output (copies :n-1 :thing combine :acc :thing)
end

show cascade 5 [combine "ha ?] "||    ; hahahahaha

to copies :n :thing :acc
  if :n = 0 [output :acc]
  output (copies :n-1 :thing combine :acc :thing)
end

print copies 5 "ha "||

implement a function to repeat a given string a specified number of times. It also demonstrates an efficient way to repeat a single character to create a new string. The code does not include the cascade feature or the ability to initialize a missing parameter.


to operate :a :b
  (print [a =] :a)
  (print [b =] :b)
  (print [a + b =] :a + :b)
  (print [a - b =] :a - :b)
  (print [a * b =] :a * :b)
  (print [a / b =] int :a / :b)
  (print [a mod b =] modulo :a :b)
end

take two integers as input from the user and calculate their sum, difference, product, integer quotient, remainder and exponentiation. It also indicates the rounding direction for quotient and the sign of the remainder. Additionally, it includes an example of the integer `divmod` operator. The code does not handle errors.


to move :n :from :to :via
  if :n = 0 [stop]
  move :n-1 :from :via :to
  (print [Move disk from] :from [to] :to)
  move :n-1 :via :to :from
end
move 4 "left "middle "right

"Implement a recursive solution to solve the Towers of Hanoi problem."


to choose :n :k
  if :k = 0 [output 1]
  output (choose :n :k-1) * (:n - :k + 1) / :k
end

show choose 5 3   ; 10
show choose 60 30 ; 1.18264581564861e+17

The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.


Works with: UCB Logo
to rotate.left :thing
  output lput first :thing butfirst :thing
end
to rotate.right :thing
  output fput last :thing butlast :thing
end

make "text "|Hello World! |
make "right? "true

to step.animation
  label :text			; graphical
  ; type char 13  type :text	; textual
  wait 6			; 1/10 second
  if button <> 0 [make "right? not :right?]
  make "text ifelse :right? [rotate.right :text] [rotate.left :text]
end

hideturtle
until [key?] [step.animation]

create a GUI window displaying a rotating "Hello World!" text. The rotation direction reverses when the text is clicked by the user.


make "val 0
do.while [make "val :val + 1  print :val] [notequal? 0 modulo :val 6]
do.until [make "val :val + 1  print :val] [equal? 0 modulo :val 6]

to my.loop :n
  make "n :n + 1
  print :n
  if notequal? 0 modulo :n 6 [my.loop :n]
end
my.loop 0

The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.


print count "|Hello World|  ; 11
print count "møøse            ; 5
print char 248   ; ø - implies ISO-Latin character set

The code calculates the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. It correctly handles Unicode code points, including Non-BMP ones, and provides the actual character counts in code points, not in code unit counts. It also has the capability to provide the string length in graphemes if the language supports it. However, it only supports ASCII encoding for Logo due to its age.


make "s "|My string|
print butfirst :s
print butlast :s
print butfirst butlast :s

The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.


to swap :i :j :a
  localmake "t item :i :a
  setitem :i :a item :j :a
  setitem :j :a :t
end
to shuffle :a
  for [i [count :a] 2] [swap 1 + random :i :i :a]
end

make "a {1 2 3 4 5 6 7 8 9 10}
shuffle :a
show :a

to slice :lst :start :finish
	local "res
	make "res []
	for "i [:start :finish 1] [
		make "j item :i :lst
		make "res se :res :j
	]
	op :res
end

to setitem :n :lst :val
	local "lhs
	local "rhs
	make "lhs slice :lst 1 :n-1
	make "rhs slice :lst :n+1 count :lst
	op (se :lhs :val :rhs)
end

to swap :i :j :a
	local "t
	make "t item :i :a
	make "a setitem :i :a item :j :a
	make "a setitem :j :a :t
	op :a
end

to shuffle :a
	for "i [count :a 2]
	[
		make "a swap 1 + random :i :i :a
	]
	op :a
end

make "a ( list 1 2 3 4 5 6 7 8 9 10 )
make "a shuffle :a
show :a

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an input array in-place. If in-place modification is not possible, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be adjusted to iterate from left to right if necessary.


; Determine if a Gregorian calendar year is leap
to leap? :year
  output (and
    equal? 0 modulo :year 4
    not member? modulo :year 400 [100 200 300]
  )
end

; Convert Gregorian calendar date to a simple day count from
; RD 1 = January 1, 1 CE
to day_number :year :month :day
  local "elapsed make "elapsed difference :year 1
  output (sum  product 365 :elapsed
              int quotient :elapsed 4
              minus int quotient :elapsed 100
              int quotient :elapsed 400
              int quotient difference product 367 :month 362 12
              ifelse lessequal? :month 2 0 ifelse leap? :year -1 -2
              :day)
end

; Find the day of the week from a day number, 0 = Sunday through 6 = Saturday
to day_of_week :day_number
  output modulo :day_number 7
end

; Find the date of the last Friday of a given month
to last_friday :year :month
  local "zero make "zero day_number :year :month 0
  local "last make "last day_number :year sum 1 :month 0
  local "wday make "wday day_of_week :last
  local "friday make "friday sum :last remainder difference -2 :wday 7
  output difference :friday :zero
end

local "year
make "year ifelse empty? :command.line 2012 :command.line

repeat 12 [
  local "month make "month #
  local "day make "day last_friday :year :month
  if (less? :month 10) [make "month word "0 :month]
  print reduce [(word ?1 "- ?2)] (list :year :month :day)
]
bye

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


Translation of: Common Lisp
Works with: UCB Logo
; some useful constants
make "lower_a ascii "a
make "lower_z ascii "z
make "upper_a ascii "A
make "upper_z ascii "Z

; encipher a single character
to encipher_char :char :key
 local "code make "code ascii :char
 local "base make "base 0
 ifelse [and (:code >= :lower_a) (:code <= :lower_z)] [make "base :lower_a] [
     if [and (:code >= :upper_a) (:code <= :upper_z)] [make "base :upper_a] ]
 ifelse [:base > 0] [
   output char (:base + (modulo ( :code - :base + :key ) 26 ))
 ] [
   output :char
 ]
end

; encipher a whole string
to caesar_cipher :string :key
  output map [encipher_char ? :key] :string
end

; Demo
make "plaintext "|The five boxing wizards jump quickly|
make "key 3
make "ciphertext caesar_cipher :plaintext :key
make "recovered  caesar_cipher :ciphertext -:key

print sentence "| Original:| :plaintext
print sentence "|Encrypted:| :ciphertext
print sentence "|Recovered:| :recovered
bye

implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigenère cipher with a key length of 1 and to Rot-13 with a key of 13.


to abs :n
  output sqrt product :n :n
end

to gcd :m :n
  output ifelse :n = 0 [ :m ] [ gcd :n modulo :m :n ]
end

to lcm :m :n
  output quotient (abs product :m :n) gcd :m :n
end

print lcm 38 46

874

calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all multiples of m until one is found that is also a multiple of n, or by using the formula lcm(m, n) = |m x n| / gcd(m, n), where gcd is the greatest common divisor. Additionally, the LCM can be found by merging the prime decompositions of both m and n.


Iterates through each element in a collection in order and prints it, using a "for each" loop or another loop if "for each" is not available in the language.


Works with: UCB Logo
to split :str :sep
  output parse map [ifelse ? = :sep ["| |] [?]] :str
end

to split :str :by [:acc []] [:w "||]
  if empty? :str [output lput :w :acc]
  ifelse equal? first :str :by ~
    [output (split butfirst :str :by lput :w :acc)] ~
    [output (split butfirst :str :by         :acc  lput first :str :w)]
end
? show split "Hello,How,Are,You,Today ",
[Hello How Are You Today]

tokenize a string by commas into an array, and display the words separated by a period, handling embedded spaces.


to gcd :a :b
  if :b = 0 [output :a]
  output gcd :b  modulo :a :b
end

calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.


"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax."


print sin 45
print cos 45
print arctan 1
make "pi (radarctan 0 1) * 2 ; based on quadrant if uses two parameters
print radsin :pi / 4
print radcos :pi / 4
print 4 * radarctan 1

print sin 45
print cos 45
print arctan 1
print radsin pi / 4
print radcos pi / 4
print 4 * radarctan 1

demonstrate the usage of trigonometric functions such as sine, cosine, tangent and their inverses in a specific programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the same angle is used for both sine calls. For inverse functions, the same number is used and its result is converted to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities. The code also includes specific features of UCB Logo and Lhogho languages.


"Code increments a numerical string, leveraging Logo's weakly typed nature to treat strings as numbers and vice versa."


to fizzbuzz :n
  output cond [ [[equal? 0 modulo :n 15] "FizzBuzz]
                [[equal? 0 modulo :n  5] "Buzz]
                [[equal? 0 modulo :n  3] "Fizz]
                [else :n] ]
end

repeat 100 [print fizzbuzz #]

to fizzbuzz :n
 make "c "
  if equal? 0 modulo :n 5 [make "c "Buzz]
  if equal? 0 modulo :n 3 [make "c word "Fizz :c]
 output ifelse equal? :c " [:n] [:c]
end

repeat 100 [print fizzbuzz repcount]

print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.


Works with: UCB Logo
to mandelbrot :left :bottom :side :size
  cs setpensize [1 1]
  make "inc :side/:size
  make "zr :left
  repeat :size [
    make "zr :zr + :inc
    make "zi :bottom
    pu
    setxy repcount - :size/2  minus :size/2
    pd
    repeat :size [
      make "zi :zi + :inc
      setpencolor count.color calc :zr :zi
      fd 1 ] ]
end

to count.color :count
  ;op (list :count :count :count)
  if :count > 256 [op 0]	; black
  if :count > 128 [op 7]	; white
  if :count >  64 [op 5]	; magenta
  if :count >  32 [op 6]	; yellow
  if :count >  16 [op 4]	; red
  if :count >   8 [op 2]	; green
  if :count >   4 [op 1]	; blue
  op 3				; cyan
end

to calc :zr :zi [:count 0] [:az 0] [:bz 0]
  if :az*:az + :bz*:bz > 4 [op :count]
  if :count > 256 [op :count]
  op (calc :zr :zi (:count + 1) (:zr + :az*:az - :bz*:bz) (:zi + 2*:az*:bz))
end

mandelbrot -2 -1.25 2.5 400

generate and draw the Mandelbrot set using various available algorithms and functions.


print apply "sum arraytolist {1 2 3 4 5}
print apply "product arraytolist {1 2 3 4 5}

Calculate the sum and product of all integers in an array.


to multiple? :n :d
  output equal? 0 modulo :n :d
end
to leapyear? :y
  output ifelse multiple? :y 100 [multiple? :y 400] [multiple? :y 4]
end

"Determines if a specified year is a leap year in the Gregorian calendar."


make "a "foo
make "b "foo
print .eq :a :b   ; true, identical symbols are reused

make "c :a
print .eq :a :c   ; true, copy a reference

make "c word :b "||  ; force a copy of the contents of a word by appending the empty word
print equal? :b :c   ; true
print .eq :b :c     ; false

"Implements a function to copy a string, distinguishing between copying the content of a string and creating an additional reference to an existing string. In the context of UCB Logo, it uses the EQUAL? predicate for content comparison and the .EQ predicate for identity comparison due to its functional language nature where words are treated as symbols."


implement two mutually recursive functions to calculate the Hofstadter Female and Male sequences. The functions use each other to compute the sequence values based on the provided formulas. If the programming language does not support mutual recursion, it should be stated.


demonstrate how to select a random element from a list.


to bsearch :value :a :lower :upper
  if :upper < :lower [output []]
  localmake "mid int (:lower + :upper) / 2
  if item :mid :a > :value [output bsearch :value :a :lower :mid-1]
  if item :mid :a < :value [output bsearch :value :a :mid+1 :upper]
  output :mid
end

The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It takes a sorted integer array, a starting point, an ending point, and a "secret value" as inputs. The algorithm can be either recursive or iterative and returns whether the number was in the array and its index if found. The code also includes variations of the binary search algorithm that return the leftmost or rightmost insertion point for the given value. It also handles potential overflow bugs.


Works with: UCB Logo version 5.6

logo file.logo - arg1 arg2 arg3

show :COMMAND.LINE
[arg1 arg2 arg3]

#! /usr/bin/logo -

file.logo arg1 arg2 arg3

The code retrieves and prints the list of command-line arguments provided to the program. It can intelligently parse these arguments. For instance, in the command line 'myprogram -c "alpha beta" -h "gamma"', the arguments after the "-" are stored in a list in the variable :COMMAND.LINE. The code also allows the execution of a logo script with arguments.


Works with: UCB Logo
make "angle 45
make "L 1
make "bob 10

to draw.pendulum
  clearscreen
  seth :angle+180		; down on screen is 180
  forward :L*100-:bob
  penup
  forward :bob
  pendown
  arc 360 :bob
end

make "G   9.80665
make "dt  1/30
make "acc 0
make "vel 0

to step.pendulum
  make "acc  -:G / :L * sin :angle
  make "vel   :vel   + :acc * :dt
  make "angle :angle + :vel * :dt
  wait :dt*60
  draw.pendulum
end

hideturtle
until [key?] [step.pendulum]

create and animate a simple physical model of a gravity pendulum.


to about :a :b
  output and [:a - :b < 1e-5] [:a - :b > -1e-5]
end

to root :n :a [:guess :a]
  localmake "next ((:n-1) * :guess + :a / power :guess (:n-1)) / n
  if about :guess :next [output :next]
  output (root :n :a :next)
end

show root 5 34   ; 2.02439745849989

Implement the principal nth root algorithm for a positive real number A.


Works with: UCB_Logo version 5.5
; useful constants
make "false 1=0
make "true  1=1
make "lf char 10
make "sp char 32

; non-digits legal in expression
make "operators (lput sp [+ - * / \( \)])

; display help message
to show_help :digits
  type lf
  print sentence quoted [Using only these digits:] :digits
  print sentence quoted [and these operators:] [* / + -]
  print quoted [\(and parentheses as needed\),]
  print quoted [enter an arithmetic expression
     which evaluates to exactly 24.]
  type lf
  print quoted [Enter \"!\" to get fresh numbers.]
  print quoted [Enter \"q\" to quit.]
  type lf
end

make "digits []
make "done false
until [done] [

  if empty? digits [
    make "digits (map [(random 9) + 1] [1 2 3 4])
  ]

  (type "Solution sp "for sp digits "? sp )
  make "expression readrawline

  ifelse [expression = "?] [

    show_help digits

  ] [ifelse [expression = "q] [

    print "Bye!
    make "done true

  ] [ifelse [expression = "!] [

    make "digits []

  ] [
    make "exprchars ` expression
    make "allowed (sentence digits operators)

    ifelse (member? false (map [[c] member? c allowed] exprchars)) [
      (print quoted [Illegal character in input.])
    ] [
      catch "error [
        make "syntax_error true
        make "testval (run expression)
        make "syntax_error false
      ]
      ifelse syntax_error [
        (print quoted [Invalid expression.])
      ] [
        ifelse (testval = 24) [
          print quoted [You win!]
          make "done true
        ] [
          (print (sentence
            quoted [Incorrect \(got ] testval quoted [instead of 24\).]))
        ]
      ]
    ]
  ]]]
]
bye

"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits."


to encode :str [:out "||] [:count 0] [:last first :str]
  if empty? :str [output (word :out :count :last)]
  if equal? first :str :last [output (encode bf :str :out :count+1 :last)]
  output (encode bf :str (word :out :count :last) 1 first :str)
end

to reps :n :w
  output ifelse :n = 0 ["||] [word :w reps :n-1 :w]
end
to decode :str [:out "||] [:count 0]
  if empty? :str [output :out]
  if number? first :str [output (decode bf :str :out 10*:count + first :str)]
  output (decode bf :str word :out reps :count first :str)
end

make "foo "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
make "rle encode :foo
show equal? :foo decode :rle

implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.


Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


Works with: MSWlogo
to clickwindow
windowCreate "root "clickWin [Click that button!!!] 0 0 100 100 []
Make "i 0
staticCreate "clickWin "clickSt [There have been no clicks yet] 0 0 100 20
buttonCreate "clickWin "clickBtn [click me] 10 20 80 20 ~
	[Make "i :i+1 ~
	ifelse :i=1 [staticUpdate "clickSt (list "clicked :i "time)] ~
	            [staticUpdate "clickSt (list "clicked :i "times)]]
end

clickwindow

"Creates a windowed application with a label and a button. The label initially displays 'There have been no clicks yet'. The button labeled 'click me' updates the label to show the number of times it has been clicked when interacted with."


The code uses a for loop to perform a countdown from 10 to 0. If the limit is less than the start, the control variable is decremented. A fourth parameter can be provided for a custom increment.


for [i 2 8 2] [type :i type "|, |] print [who do we appreciate?]

demonstrate a for-loop with a step-value greater than one.


to ack :i :j
  if :i = 0 [output :j+1]
  if :j = 0 [output ack :i-1 1]
  output ack :i-1 ack :i :j-1
end

Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.


to try :files :diag1 :diag2 :tried
  if :files = 0 [make "solutions :solutions+1  show :tried  stop]
  localmake "safe (bitand :files :diag1 :diag2)
  until [:safe = 0] [
    localmake "f bitnot bitand :safe minus :safe
    try bitand :files :f  ashift bitand :diag1 :f -1  (ashift bitand :diag2 :f 1)+1  fput bitnot :f :tried
    localmake "safe bitand :safe :safe-1
  ]
end

to queens :n
  make "solutions 0
  try (lshift 1 :n)-1 -1 -1 []
  output :solutions
end

print queens 8  ; 92

"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N."


to combine-arrays :a1 :a2
  output listtoarray sentence arraytolist :a1 arraytolist :a2
end
show combine-arrays {1 2 3} {4 5 6}   ; {1 2 3 4 5 6}

demonstrate how to concatenate two arrays, possibly using the '+' operator or the 'COMBINE' and 'SENTENCE' functions.


The code defines two functions, a and b, both of which accept and return a boolean value and print their names when called. The code then calculates the values of two equations, x = a(i) and b(j), and y = a(i) or b(j), using short-circuit evaluation to ensure that function b is only called when necessary. If the programming language does not support short-circuit evaluation, this is achieved using nested if statements. The AND and OR operators are used in a way that evaluates expressions from left to right until the overall value can be determined.


make "blocks [[B O] [X K] [D Q] [C P] [N A] [G T] [R E] [T G] [Q D] [F S]
              [J W] [H U] [V I] [A N] [O B] [E R] [F S] [L Y] [P C] [Z M]]

to can_make? :word [:avail :blocks]
  if empty? :word [output "true]
  local "letter make "letter first :word
  foreach :avail [
    local "i     make "i     #
    local "block make "block ?
    if member? :letter :block [
      if (can_make? bf :word filter [notequal? # :i] :avail) [output "true]
    ]
  ]
  output "false
end

foreach [A BARK BOOK TREAT COMMON SQUAD CONFUSE] [
  print sentence word ? ": can_make? ?
]

bye

"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed."


to increment_octal :n
  ifelse [empty? :n] [
    output 1
  ] [
    local "last
    make "last last :n
    local "butlast
    make "butlast butlast :n
    make "last sum :last 1
    ifelse [:last < 8] [
      output word :butlast :last
    ] [
      output word (increment_octal :butlast) 0
    ]
  ]
end

make "oct 0
while ["true] [
  print :oct
  make "oct increment_octal :oct
]

generate a sequential count in octal format, starting from zero and incrementing by one. Each number is printed on a separate line and the count continues until the program is terminated or the maximum value of the numeric type is reached. The program avoids the use of built-in octal-formatting for efficiency and instead manually increments a string.


to swap :s1 :s2
  localmake "t thing :s1
  make :s1 thing :s2
  make :s2 :t
end

make "a 4
make "b "dog
swap "a "b        ; pass the names of the variables to swap
show list :a :b  ; [dog 4]

implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.


to palindrome? :w
  output equal? :w reverse :w
end

implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.


class Stack[T] {
  private var items = List[T]()

  def isEmpty = items.isEmpty

  def peek = items match {
    case List()       => error("Stack empty")
    case head :: rest => head
  }

  def pop = items match {
    case List()       => error("Stack empty")
    case head :: rest => items = rest; head
  }

  def push(value: T) = items = value +: items
}

import collection.mutable.{ Stack => Stak }

class Stack[T] extends Stak[T] {
  override def pop: T = {
    if (this.length == 0) error("Can't Pop from an empty Stack.")
    else super.pop
  }
  def peek: T = this.head
}A test could be:object StackTest extends App {

  val stack = new Stack[String]

  stack.push("Peter Pan")
  stack.push("Suske & Wiske", "Alice in Wonderland")

  assert(stack.peek == "Alice in Wonderland")
  assert(stack.pop() == "Alice in Wonderland")
  assert(stack.pop() == "Suske & Wiske")
  assert(stack.pop() == "Peter Pan")
  println("Completed without errors")
}

implement a stack with basic operations including push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and is accessed through its top. The push operation stores a new element onto the stack top, pop operation returns and removes the last pushed stack element, and empty operation checks if the stack contains no elements. The top operation returns the topmost element without modifying the stack.


Recursive[edit]
def fib(i: Int): Int = i match {
  case 0 => 0
  case 1 => 1
  case _ => fib(i - 1) + fib(i - 2)
}
Lazy sequence[edit]
lazy val fib: LazyList[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map { case (a, b) => a + b }
Tail recursive[edit]
import scala.annotation.tailrec
@tailrec
final def fib(x: Int, prev: BigInt = 0, next: BigInt = 1): BigInt = x match {
  case 0 => prev
  case _ => fib(x - 1, next, next + prev)
}
foldLeft[edit]
// Fibonacci using BigInt with LazyList.foldLeft optimized for GC (Scala v2.13 and above)
// Does not run out of memory for very large Fibonacci numbers
def fib(n: Int): BigInt = {

  def series(i: BigInt, j: BigInt): LazyList[BigInt] = i #:: series(j, i + j)

  series(1, 0).take(n).foldLeft(BigInt("0"))(_ + _)
}

// Small test
(0 to 13) foreach {n => print(fib(n).toString + " ")}

// result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233
Iterator[edit]
val it: Iterator[Int] = Iterator.iterate((0, 1)) { case (a, b) => (b, a + b) }.map(_._1)

def fib(n: Int): Int = it.drop(n).next()

// example:
println(it.take(13).mkString(",")) // prints: 0,1,1,2,3,5,8,13,21,34,55,89,144

generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.


select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.


Library: Scala
object Substring {
  // Ruler             1         2         3         4         5         6
  //         012345678901234567890123456789012345678901234567890123456789012
  val str = "The good life is one inspired by love and guided by knowledge."
  val (n, m) = (21, 16) // An one-liner to set n = 21, m = 16

  // Starting from n characters in and of m length
  assert("inspired by love" == str.slice(n, n + m))

  // Starting from n characters in, up to the end of the string
  assert("inspired by love and guided by knowledge." == str.drop(n))

  // Whole string minus last character
  assert("The good life is one inspired by love and guided by knowledge" == str.init)

  // Starting from a known character within the string and of m length
  assert("life is one insp" == str.dropWhile(_ != 'l').take(m) )

  // Starting from a known substring within the string and of m length
  assert("good life is one" == { val i = str.indexOf("good"); str.slice(i, i + m) })
  // Alternatively
  assert("good life is one" == str.drop(str.indexOf("good")).take(m))
}

- Extracts a substring starting from the nth character of a specific length m.
- Extracts a substring starting from the nth character up to the end of the string.
- Returns the entire string excluding the last character.
- Extracts a substring starting from a known character within the string of length m.
- Extracts a substring starting from a known substring within the string of length m.
- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.
- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.


"asdf".reverse

"asdf".foldRight("")((a,b) => b+a)

def reverse(s: String) = {
  import java.text.{Normalizer,BreakIterator}
  val norm = Normalizer.normalize(s, Normalizer.Form.NFKC) // waﬄe -> waffle (optional)
  val it = BreakIterator.getCharacterInstance
  it setText norm
  def break(it: BreakIterator, prev: Int, result: List[String] = Nil): List[String] = it.next match {
    case BreakIterator.DONE => result
    case cur => break(it, cur, norm.substring(prev, cur) :: result)
  }
  break(it, it.first).mkString
}

"Reverses a given string while preserving the order of Unicode combining characters. For instance, "asdf" is transformed to "fdsa" and "as⃝df̅" is transformed to "f̅ds⃝a". The code also handles supplementary characters but does not preserve the order of newline characters or consider directionality. The output is displayed in bytes on Windows due to REPL's inability to handle Unicode."


object Dijkstra {

  type Path[Key] = (Double, List[Key])

  def Dijkstra[Key](lookup: Map[Key, List[(Double, Key)]], fringe: List[Path[Key]], dest: Key, visited: Set[Key]): Path[Key] = fringe match {
    case (dist, path) :: fringe_rest => path match {case key :: path_rest =>
      if (key == dest) (dist, path.reverse)
      else {
        val paths = lookup(key).flatMap {case (d, key) => if (!visited.contains(key)) List((dist + d, key :: path)) else Nil}
        val sorted_fringe = (paths ++ fringe_rest).sortWith {case ((d1, _), (d2, _)) => d1 < d2}
        Dijkstra(lookup, sorted_fringe, dest, visited + key)
      }
    }
    case Nil => (0, List())
  }

  def main(x: Array[String]): Unit = {
    val lookup = Map(
      "a" -> List((7.0, "b"), (9.0, "c"), (14.0, "f")),
      "b" -> List((10.0, "c"), (15.0, "d")),
      "c" -> List((11.0, "d"), (2.0, "f")),
      "d" -> List((6.0, "e")),
      "e" -> List((9.0, "f")),
      "f" -> Nil
    )
    val res = Dijkstra[String](lookup, List((0, List("a"))), "e", Set())
    println(res)
  }
}

implement Dijkstra's algorithm to find the shortest path from a given source node to all other nodes in a directed and weighted graph. The graph is represented by an adjacency matrix or list, and the output is a set of edges depicting the shortest path to each destination node. The algorithm is run on a specific graph with nodes labeled 'a' through 'f' and the shortest path from node 'a' to nodes 'e' and 'f' is determined.