main(){
	// Dart uses Lists which dynamically resize by default
	final growable = [ 1, 2, 3 ];

        // Add to the list using the add method
	growable.add(4);

	print('growable: $growable');

	// You can pass an int to the constructor to create a fixed sized List
	final fixed = List(3);

	// We must assign each element individually using the Subscript operator
	// using .add would through an error
	fixed[0] = 'one';
	fixed[1] = 'two';
	fixed[2] = 'three';

	print('fixed: $fixed');

	// If we want to create a fixed list all at once we can use the of constructor
	// Setting growable to false is what makes it fixed
	final fixed2 = List.of( [ 1.5, 2.5, 3.5 ], growable: false);

	print('fixed2: $fixed2');

	// A potential gotcha involving the subscript operator [] might surprise JavaScripters
	// One cannot add new elements to a List using the subscript operator
	// We can only assign to existing elements, even if the List is growable

	final gotcha = [ 1, 2 ];
	// gotcha[2] = 3 would cause an error in Dart, but not in JavaScript
	// We must first add the new element using .add
	gotcha.add(3);
	// Now we can modify the existing elements with the subscript
	gotcha[2] = 4;

	print('gotcha: $gotcha');

}

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.


String capitalize(String string) {
  if (string.isEmpty) {
    return string;
  }
  return string[0].toUpperCase() + string.substring(1);
}

void main() {
  var s = 'alphaBETA';
  print('Original string: $s');
  print('To Lower case:   ${s.toLowerCase()}');
  print('To Upper case:   ${s.toUpperCase()}');
  print('To Capitalize:   ${capitalize(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.


String loopPlusHalf(start, end) {
  var result = '';
  for(int i = start; i <= end; i++) {
    result += '$i';
    if(i == end) {
      break;
    }
    result += ', ';
  }
  return result;
}

void main() {
  print(loopPlusHalf(1, 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.


import 'dart:math';

factors(n)
{
 var factorsArr = [];
 factorsArr.add(n);
 factorsArr.add(1);
 for(var test = n - 1; test >= sqrt(n).toInt(); test--)
  if(n % test == 0)
  {
   factorsArr.add(test);
   factorsArr.add(n / test);
  }
 return factorsArr;
}

void main() {
  print(factors(5688));
}

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.


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.


main() {
	var rosettaCode = { // Type is inferred to be Map<String, String>
		'task': 'Associative Array Creation'
	};

	rosettaCode['language'] = 'Dart';

	// The update function can be used to update a key using a callback
	rosettaCode.update( 'is fun',  // Key to update
		(value) => "i don't know", // New value to use if key is present
		ifAbsent: () => 'yes!' // Value to use if key is absent
	);

	assert( rosettaCode.toString() == '{task: Associative Array Creation, language: Dart, is fun: yes!}');

	// If we type the Map with dynamic keys and values, it is like a JavaScript object
	Map<dynamic, dynamic> jsObject = {
		'key': 'value',
		1: 2,
		1.5: [ 'more', 'stuff' ],
		#doStuff: () => print('doing stuff!') // #doStuff is a symbol, only one instance of this exists in the program. Would be :doStuff in Ruby
	};

	print( jsObject['key'] );
	print( jsObject[1] );

	for ( var value in jsObject[1.5] )
		print('item: $value');

	jsObject[ #doStuff ](); // Calling the function

	print('\nKey types:');
	jsObject.keys.forEach( (key) => print( key.runtimeType ) );
}

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


int fact(int n) {
  if(n<0) {
    throw new IllegalArgumentException('Argument less than 0');
  }
  return n==0 ? 1 : n*fact(n-1);
}

main() {
  print(fact(10));
  print(fact(-1));
}
int fact(int n) {
  if(n<0) {
    throw new IllegalArgumentException('Argument less than 0');
  }
  int res=1;
  for(int i=1;i<=n;i++) {
    res*=i;
  }
  return res;
}

main() {
  print(fact(10));
  print(fact(-1));
}

The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.


num dot(List<num> A, List<num> B){
  if (A.length != B.length){
    throw new Exception('Vectors must be of equal size');
  }
  num result = 0;
  for (int i = 0; i < A.length; i++){
    result += A[i] * B[i];
  }
  return result;
}

void main(){
  var l = [1,3,-5];
  var k = [4,-2,-1];
  print(dot(l,k));
}

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].


import 'dart:math';
import 'dart:io';

main() {
  final n = (1 + new Random().nextInt(10)).toString();
  print("Guess which number I've chosen in the range 1 to 10");
  do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync());
  print("\nWell guessed!");
}

"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing."


String binary(int n) {
  if(n<0)
    throw new IllegalArgumentException("negative numbers require 2s complement");
  if(n==0) return "0";
  String res="";
  while(n>0) {
    res=(n%2).toString()+res;
    n=(n/2).toInt();
  }
  return res;
}

main() {
  print(binary(0));
  print(binary(1));
  print(binary(5));
  print(binary(10));
  print(binary(50));
  print(binary(9000));
  print(binary(65535));
  print(binary(0xaa5511ff));
  print(binary(0x123456789abcde));
  // fails due to precision limit
  print(binary(0x123456789abcdef));
}

generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.


import 'dart:math';

class Haversine {
  static final R = 6372.8; // In kilometers

  static double haversine(double lat1, lon1, lat2, lon2) {
    double dLat = _toRadians(lat2 - lat1);
    double dLon = _toRadians(lon2 - lon1);
    lat1 = _toRadians(lat1);
    lat2 = _toRadians(lat2);
    double a = pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(lat1) * cos(lat2);
    double c = 2 * asin(sqrt(a));
    return R * c;
  }

  static double _toRadians(double degree) {
    return degree * pi / 180;
  }

  static void main() {
    print(haversine(36.12, -86.67, 33.94, -118.40));
  }
}

Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.


import 'dart:io';
void main(){
  var url = 'http://rosettacode.org';
  var client = new HttpClient();
  client.getUrl(Uri.parse(url))
        .then((HttpClientRequest request)   => request.close())
        .then((HttpClientResponse response) => response.pipe(stdout));
}

"Code accesses and prints the content of a specified URL to the console using a stand-alone VM. Note: This does not cover HTTPS requests."


RegExp regexp = new RegExp(r'\w+\!');

String capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}';

void main(){
  String hello = 'hello hello! world world!';
  String hellomodified = hello.replaceAllMapped(regexp, capitalize);
  print(hello);
  print(hellomodified);
}

"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression."


main() {
  moveit(from,to) {
    print("move ${from} ---> ${to}");
  }

  hanoi(height,toPole,fromPole,usePole) {
    if (height>0) {
      hanoi(height-1,usePole,fromPole,toPole);
      moveit(fromPole,toPole);
      hanoi(height-1,toPole,usePole,fromPole);
    }
  }

  hanoi(3,3,1,2);
}

main() {
  String say(String from, String to) => "$from ---> $to";

  hanoi(int height, int toPole, int fromPole, int usePole) {
    if (height > 0) {
      hanoi(height - 1, usePole, fromPole, toPole);
      print(say(fromPole.toString(), toPole.toString()));
      hanoi(height - 1, toPole, usePole, fromPole);
    }
  }

  hanoi(3, 3, 1, 2);
}

implement a recursive solution to solve the Towers of Hanoi problem, adhering to the style guide provided by dartlang.org and optionally including static type annotations.


void main() {
    List<int> a = shellSort([1100, 2, 56, 200, -52, 3, 99, 33, 177, -199]);
    print('$a');
}

shellSort(List<int> array) {
	int n = array.length;

        // Start with a big gap, then reduce the gap
        for (int gap = n~/2; gap > 0; gap ~/= 2)
        {
            // Do a gapped insertion sort for this gap size.
            // The first gap elements a[0..gap-1] are already
            // in gapped order keep adding one more element
            // until the entire array is gap sorted
            for (int i = gap; i < n; i += 1)
            {
                // add a[i] to the elements that have been gap
                // sorted save a[i] in temp and make a hole at
                // position i
                int temp = array[i];

                // shift earlier gap-sorted elements up until
                // the correct location for a[i] is found
                int j;
                for (j = i; j >= gap && array[j - gap] > temp; j -= gap)
                    array[j] = array[j - gap];

                // put temp (the original a[i]) in its correct
                // location
                array[j] = temp;
            }
        }
  return array;
}

implement the Shell sort algorithm to sort an array of elements. The algorithm, invented by Donald Shell in 1959, uses a diminishing increment sequence for interleaved insertion sorts. The increment size reduces with each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, which is the best case scenario for insertion sort. The algorithm works with any sequence that ends in 1, but sequences with a geometric increment ratio of about 2.2 have been found to be most effective.


Library: Flutter

import 'package:flutter/material.dart';
import 'dart:async' show Timer;

void main() {

  var timer = const Duration( milliseconds: 75 ); // How often to update i.e. how fast the animation is

  runApp(MaterialApp (
    home: Scaffold (
      body: Center (
        child: AnimatedText( timer )
      )
    )
  ));
}

class AnimatedText extends StatefulWidget {

  final Duration period; // Time period for update

  AnimatedText( this.period );
  @override
  _AnimatedText createState() => _AnimatedText( period );
}

class _AnimatedText extends State<AnimatedText> {

  bool forward = true; // Text should go forward?

  Timer timer; // Timer Objects allow us to do things based on a period of time
  // We want to get an array of characters, but Dart does not have a char type
  // Below is the equivalent code
  var _text =  'Hello World!      '.runes // .runes gives us the unicode number of each character
    .map( (code) => String.fromCharCode(code) ) // Map all these codes to Strings containing the single character
    .toList(); // Conver to a List

  _AnimatedText( Duration period ){
    timer = Timer.periodic( period , (_){
      setState((){ // Set state forces the gui elements to be redrawn
        shiftText();

      });
    });
  }

  String get text => _text.join(''); // Getter, joins the list of chars into a string

  void shiftText() {
    if (forward) { // If we should go forward
      var last = _text.removeLast(); // Remove the last char

      _text.insert( 0, last); // Insert it at the front

    } else { // If we should go backward
      var first = _text.removeAt(0); // Remove the first char

      _text.insert( _text.length, first ); // Insert it at the end
    }

 }

  @override
  Widget build(BuildContext context) {
    return GestureDetector( // GestureDetector lets us capture events
      onTap: () => forward = !forward, // on Tap (Click in browser) invert the forward bool
      child: Text(
        text, // Call the text getter to get the shifted string
        style: TextStyle( // Styling
          fontSize: 50,
          color: Colors.grey[600]
        )
      )

    );
  }

}

Library: Html Dom
import 'dart:html';
import 'dart:async';

const frameTime = const Duration(milliseconds: 100);

void main() {
  String text = "Hello World! ";
  bool rotateRight = true;

  Element writeHere =
      querySelector('#output'); // assumes you have a pre with that ID
  writeHere.onClick.listen((event) => rotateRight = !rotateRight);

  new Timer.periodic(frameTime, (_) {
    text = changeText(text, rotateRight);
    writeHere.text = text;
  });
}

String changeText(extt, rotateRight) {
  if (rotateRight) {
    return extt.substring(extt.length - 1) + extt.substring(0, extt.length - 1);
  } else {
    return extt.substring(1) + extt.substring(0, 1);
  }
}

Creates an animated GUI window displaying the text "Hello World!". The text appears to rotate right by periodically shifting the last letter to the front. The direction of rotation reverses when the user clicks on the text.


void main() {
  int val = 0;
  do {
    val++;
    print(val);
  } while (val % 6 != 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.


void main() {
  String word = "Premier League";
  print("Without first letter: ${word.substring(1)} !");
  print("Without last letter: ${word.substring(0, word.length - 1)} !");
  print("Without first and last letter: ${word.substring(1, word.length - 1)} !");
}

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.


import 'dart:io';

void main() {
  stdout.write("Goodbye, World!");
}

"Display the string 'Goodbye, World!' without appending a newline at the end."


Library: Flutter

import 'package:flutter/material.dart';

main() => runApp( OutputLabel() );

class OutputLabel extends StatefulWidget {
  @override
  _OutputLabelState createState() => _OutputLabelState();
}

class _OutputLabelState extends State<OutputLabel> {
  String output = "output"; // This will be displayed in an output text field

  TextEditingController _stringInputController = TextEditingController(); // Allows us to get the text from a text field
  TextEditingController _numberInputController = TextEditingController();

  @override
  Widget build( BuildContext context ) {
    return MaterialApp(
      debugShowCheckedModeBanner: false, // Disable debug banner in top right
      home: Scaffold ( // Scaffold provides a layout for the app
        body: Center ( // Everything in the center widget will be centered
          child: Column ( // All the widgets will be in a column
            children: <Widget> [
              SizedBox( height: 25 ), // Space between top and text field

              TextField ( // String input Text Field
                controller: _stringInputController, // Add input controller so we can grab text
                textAlign: TextAlign.center, // Center text
                decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Enter a string...'), // Border and default text
              ), // end TextField

              SizedBox( height: 10 ), // Space between text fields

              TextField ( // Number input Text Field
                controller: _numberInputController, // Add input controller so we can grab text
                textAlign: TextAlign.center, // Center text
                decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Enter 75000'), // Border and default text
              ), // end TextField

              FlatButton ( // Submit Button
                child: Text('Submit Data'), // Button Text
                color: Colors.blue[400] // button color
                onPressed: () { // On pressed Callback for button
                  setState( () {
                    output = ''; // Reset output

                    int number; // Int to store number in

                    var stringInput = _stringInputController.text ?? ''; // Get the input from the first field, if it is null set it to an empty string

                    var numberString = _numberInputController.text ?? ''; // Get the input from the second field, if it is null set it to an empty string

                    if ( stringInput == '')  { // If first field is empty
                      output = 'Please enter something in field 1\n';
                      return;
                    }

                    if (_numberInputController.text == '') { // If second field is empty
                      output += 'Please enter something in field 2';
                      return;
                    } else { // If we got an input in the second field

                      try {
                        number = int.parse( numberString ); // Parse numberString into an int

                        if ( number == 75000 )
                          output = 'text output: $stringInput\nnumber: $number'; // Grabs the text from the input controllers and changes the string
                        else
                          output = '$number is not 75000!';

                      } on FormatException { // If a number is not entered in second field
                          output = '$numberString is not a number!';
                      }

                    }

                  });
                }
              ), // End FlatButton

              Text( output ) // displays output

            ]
          )
        )
      )
    );
  }
}

The code enables the input of a string and the integer 75000 via a graphical user interface. It features two text fields, a button, and an output label. The code can be viewed on Dartpad.


class Caesar {
  int _key;

  Caesar(this._key);

  int _toCharCode(String s) {
    return s.charCodeAt(0);
  }

  String _fromCharCode(int ch) {
    return new String.fromCharCodes([ch]);
  }

  String _process(String msg, int offset) {
    StringBuffer sb=new StringBuffer();
    for(int i=0;i<msg.length;i++) {
      int ch=msg.charCodeAt(i);
      if(ch>=_toCharCode('A')&&ch<=_toCharCode('Z')) {
        sb.add(_fromCharCode(_toCharCode("A")+(ch-_toCharCode("A")+offset)%26));
      }
      else if(ch>=_toCharCode('a')&&ch<=_toCharCode('z')) {
        sb.add(_fromCharCode(_toCharCode("a")+(ch-_toCharCode("a")+offset)%26));
      } else {
        sb.add(msg[i]);
      }
    }
    return sb.toString();
  }

  String encrypt(String msg) {
    return _process(msg, _key);
  }

  String decrypt(String msg) {
    return _process(msg, 26-_key);
   }
}

void trip(String msg) {
  Caesar cipher=new Caesar(10);

  String enc=cipher.encrypt(msg);
  String dec=cipher.decrypt(enc);
  print("\"$msg\" encrypts to:");
  print("\"$enc\" decrypts to:");
  print("\"$dec\"");
  Expect.equals(msg,dec);
}

main() {
  Caesar c2=new Caesar(2);
  print(c2.encrypt("HI"));
  Caesar c20=new Caesar(20);
  print(c20.encrypt("HI"));

  // try a few roundtrips

  trip("");
  trip("A");
  trip("z");
  trip("Caesar cipher");
  trip(".-:/\"\\!");
  trip("The Quick Brown Fox Jumps Over The Lazy Dog.");
}

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.


main() {
	int x=8;
  int y=12;
int z= gcd(x,y);
  var lcm=(x*y)/z;
  print('$lcm');
  }

int gcd(int a,int b)
{
  if(b==0)
    return a;
  if(b!=0)
    return gcd(b,a%b);
}

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 the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


main() {
  for (int i = 1; i <= 100; i++) {
    List<String> out = [];
    if (i % 3 == 0)
      out.add("Fizz");
    if (i % 5 == 0)
      out.add("Buzz");
    print(out.length > 0 ? out.join("") : i);
  }
}

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'.


class Complex {
  double _r,_i;

  Complex(this._r,this._i);
  double get r => _r;
  double get i => _i;
  String toString() => "($r,$i)";

  Complex operator +(Complex other) => new Complex(r+other.r,i+other.i);
  Complex operator *(Complex other) =>
      new Complex(r*other.r-i*other.i,r*other.i+other.r*i);
  double abs() => r*r+i*i;
}

void main() {
  double start_x=-1.5;
  double start_y=-1.0;
  double step_x=0.03;
  double step_y=0.1;

  for(int y=0;y<20;y++) {
    String line="";
    for(int x=0;x<70;x++) {
      Complex c=new Complex(start_x+step_x*x,start_y+step_y*y);
      Complex z=new Complex(0.0, 0.0);
      for(int i=0;i<100;i++) {
        z=z*(z)+c;
        if(z.abs()>2) {
          break;
        }
      }
      line+=z.abs()>2 ? " " : "*";
    }
    print(line);
  }
}

generate and draw the Mandelbrot set using various algorithms and functions. The code is implemented in Google Dart and operates on http://try.dartlang.org/. It utilizes an incomplete Complex class that supports operator overloading. Note that due to the novelty of the language, the code may become obsolete in the future.


class Leap {
  bool leapYear(num year) {
    return (year % 400 == 0) || (( year % 100 != 0) && (year % 4 == 0));

  bool isLeapYear(int year) =>
    (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
  // Source: https://api.flutter.dev/flutter/quiver.time/isLeapYear.html
  }
}

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


implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.


import 'dart:math';

void main() {
  final array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
  int i;

  for (i = 1; i < 30; i++) {
    var intValue = Random().nextInt(i) % 10;
    print(array[intValue]);
  }
}

demonstrate how to select a random element from a list.


main(List<String> args) {
    for(var arg in args)
        print(arg);
}

The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c "alpha beta" -h "gamma"'. It also includes functionalities for intelligent parsing of these arguments.


import 'dart:convert' show jsonDecode, jsonEncode;

main(){
	var json_string = '''
	{
		"rosetta_code": {
			"task": "json",
			"language": "dart",
			"descriptions": [ "fun!", "easy to learn!", "awesome!" ]
		}
	}
	''';

	// decode string into Map<String, dynamic>
	var json_object = jsonDecode(json_string);

	for ( var description in json_object["rosetta_code"]["descriptions"] )
		print( "dart is $description" );

	var dart = {
		"compiled": true,
		"interpreted": true,
		"creator(s)":[ "Lars Bak", "Kasper Lund"],
		"development company": "Google"
	};

	var as_json_text = jsonEncode(dart);

	assert(as_json_text == '{"compiled":true,"interpreted":true,"creator(s)":["Lars Bak","Kasper Lund"],"development company":"Google"}');
}

"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON."


void main() {
  for (var i = 10; i >= 0; --i) {
    print(i);
  }
}

The code performs a countdown from 10 to 0 using a downward for loop.


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


Implement the Ackermann function, a non-primitive recursive function that takes two non-negative arguments and returns a rapidly growing value. The function should ideally support arbitrary precision due to its fast growth rate, but it's not mandatory. The function does not utilize caching, resulting in longer execution times for larger inputs.


/**
Return true if queen placement q[n] does not conflict with
other queens q[0] through q[n-1]
*/
isConsistent(List q, int n) {
  for (int i=0; i<n; i++) {
    if (q[i] == q[n]) {
      return false; // Same column
    }

    if ((q[i] - q[n]) == (n - i)) {
      return false; // Same major diagonal
    }

    if ((q[n] - q[i]) == (n - i)) {
      return false; // Same minor diagonal
    }
  }

  return true;
}

/**
Print out N-by-N placement of queens from permutation q in ASCII.
*/
printQueens(List q) {
  int N = q.length;
  for (int i=0; i<N; i++) {
    StringBuffer sb = new StringBuffer();
    for (int j=0; j<N; j++) {
      if (q[i] == j) {
        sb.write("Q ");
      } else {
        sb.write("* ");
      }
    }
    print(sb.toString());
  }
  print("");
}

/**
Try all permutations using backtracking
*/
enumerate(int N) {
  var a = new List(N);
  _enumerate(a, 0);
}

_enumerate(List q, int n) {
  if (n == q.length) {
    printQueens(q);
  } else {
    for (int i = 0; i < q.length; i++) {
      q[n] = i;
      if (isConsistent(q, n)){
        _enumerate(q, n+1);
      }
    }
  }
}

void main() {
  enumerate(4);
}

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


List solveKnapsack(items, maxWeight) {
  int MIN_VALUE=-100;
  int N = items.length; // number of items
  int W = maxWeight; // maximum weight of knapsack

  List profit = new List(N+1);
  List weight = new List(N+1);

  // generate random instance, items 1..N
  for(int n = 1; n<=N; n++) {
    profit[n] = items[n-1][2];
    weight[n] = items[n-1][1];

  }

  // opt[n][w] = max profit of packing items 1..n with weight limit w
  // sol[n][w] = does opt solution to pack items 1..n with weight limit w include item n?
  List<List<int>> opt = new List<List<int>>(N+1);
  for (int i=0; i<N+1; i++) {
    opt[i] = new List<int>(W+1);
    for(int j=0; j<W+1; j++) {
      opt[i][j] = MIN_VALUE;
    }
  }

  List<List<bool>> sol = new List<List<bool>>(N+1);
  for (int i=0; i<N+1; i++) {
    sol[i] = new List<bool>(W+1);
    for(int j=0; j<W+1; j++) {
      sol[i][j] = false;
    }
  }

  for(int n=1; n<=N; n++) {
    for (int w=1; w <= W; w++) {
      // don't take item n
      int option1 = opt[n-1][w];

      // take item n
      int option2 = MIN_VALUE;
      if (weight[n] <= w) {
        option2 = profit[n] + opt[n-1][w - weight[n]];
      }

      // select better of two options
      opt[n][w] = Math.max(option1, option2);
      sol[n][w] = (option2 > option1);
    }
  }

  // determine which items to take
  List<List> packItems = new List<List>();
  List<bool> take = new List(N+1);
  for (int n = N, w = W; n > 0; n--) {
    if (sol[n][w]) {
      take[n] = true;
      w = w - weight[n];
      packItems.add(items[n-1]);
    } else {
      take[n] = false;
    }
  }

  return packItems;

}

main() {
  List knapsackItems = [];
  knapsackItems.add(["map", 9, 150]);
  knapsackItems.add(["compass", 13, 35]);
  knapsackItems.add(["water", 153, 200]);
  knapsackItems.add(["sandwich", 50, 160]);
  knapsackItems.add(["glucose", 15, 60]);
  knapsackItems.add(["tin", 68, 45]);
  knapsackItems.add(["banana", 27, 60]);
  knapsackItems.add(["apple", 39, 40]);
  knapsackItems.add(["cheese", 23, 30]);
  knapsackItems.add(["beer", 52, 10]);
  knapsackItems.add(["suntan cream", 11, 70]);
  knapsackItems.add(["camera", 32, 30]);
  knapsackItems.add(["t-shirt", 24, 15]);
  knapsackItems.add(["trousers", 48, 10]);
  knapsackItems.add(["umbrella", 73, 40]);
  knapsackItems.add(["waterproof trousers", 42, 70]);
  knapsackItems.add(["waterproof overclothes", 43, 75]);
  knapsackItems.add(["note-case", 22, 80]);
  knapsackItems.add(["sunglasses", 7, 20]);
  knapsackItems.add(["towel", 18, 12]);
  knapsackItems.add(["socks", 4, 50]);
  knapsackItems.add(["book", 30, 10]);
  int maxWeight = 400;
  Stopwatch sw = new Stopwatch.start();
  List p = solveKnapsack(knapsackItems, maxWeight);
  sw.stop();
  int totalWeight = 0;
  int totalValue = 0;
  print(["item","profit","weight"]);
  p.forEach((var i) { print("${i}"); totalWeight+=i[1]; totalValue+=i[2]; });
  print("Total Value = ${totalValue}");
  print("Total Weight = ${totalWeight}");
  print("Elapsed Time = ${sw.elapsedInMs()}ms");

}

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.


bool isPalindrome(String s){
  for(int i = 0; i < s.length/2;i++){
    if(s[i] != s[(s.length-1) -i])
      return false;
  }
  return true;
}

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.


int F(int n, int x, int y) {
  if (n == 0) {
    return x + y;
  } else if (y == 0) {
    return x;
  }

  return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y);
}

void main() {
  print('F(1,3,3) = ${F(1, 3, 3)}');
}

Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.


import std.array;

class Stack(T) {
    private T[] items;

    @property bool empty() { return items.empty(); }

    void push(T top) { items ~= top; }

    T pop() {
        if (this.empty)
            throw new Exception("Empty Stack.");
        auto top = items.back;
        items.popBack();
        return top;
    }
}

void main() {
    auto s = new Stack!int();
    s.push(10);
    s.push(20);
    assert(s.pop() == 20);
    assert(s.pop() == 10);
    assert(s.empty());
}

Implement a stack class supporting basic operations such as push (adding an element to the top of the stack), pop (removing and returning the topmost element), and empty (checking if the stack is empty). The stack follows a last in, first out (LIFO) access policy.


import std.stdio, std.conv, std.algorithm, std.math;

long sgn(alias unsignedFib)(int n) { // break sign manipulation apart
    immutable uint m = (n >= 0) ? n : -n;
    if (n < 0 && (n % 2 == 0))
        return -unsignedFib(m);
    else
        return unsignedFib(m);
}

long fibD(uint m) { // Direct Calculation, correct for abs(m) <= 84
    enum sqrt5r =  1.0L / sqrt(5.0L);         //  1 / sqrt(5)
    enum golden = (1.0L + sqrt(5.0L)) / 2.0L; // (1 + sqrt(5)) / 2
    return roundTo!long(pow(golden, m) * sqrt5r);
}

long fibI(in uint m) pure nothrow { // Iterative
    long thisFib = 0;
    long nextFib = 1;
    foreach (i; 0 .. m) {
        long tmp = nextFib;
        nextFib += thisFib;
        thisFib  = tmp;
    }
    return thisFib;
}

long fibR(uint m) { // Recursive
    return (m < 2) ? m : fibR(m - 1) + fibR(m - 2);
}

long fibM(uint m) { // memoized Recursive
    static long[] fib = [0, 1];
    while (m >= fib.length )
        fib ~= fibM(m - 2) + fibM(m - 1);
    return fib[m];
}

alias sgn!fibD sfibD;
alias sgn!fibI sfibI;
alias sgn!fibR sfibR;
alias sgn!fibM sfibM;

auto fibG(in int m) { // generator(?)
    immutable int sign = (m < 0) ? -1 : 1;
    long yield;

    return new class {
        final int opApply(int delegate(ref int, ref long) dg) {
            int idx = -sign; // prepare for pre-increment
            foreach (f; this)
                if (dg(idx += sign, f))
                    break;
            return 0;
        }

        final int opApply(int delegate(ref long) dg) {
            long f0, f1 = 1;
            foreach (p; 0 .. m * sign + 1) {
                if (sign == -1 && (p % 2 == 0))
                    yield = -f0;
                else
                    yield = f0;
                if (dg(yield)) break;
                auto temp = f1;
                f1 = f0 + f1;
                f0 = temp;
            }
            return 0;
        }
    };
}

void main(in string[] args) {
    int k = args.length > 1 ? to!int(args[1]) : 10;
    writefln("Fib(%3d) = ", k);
    writefln("D : %20d <- %20d + %20d",
             sfibD(k), sfibD(k - 1), sfibD(k - 2));
    writefln("I : %20d <- %20d + %20d",
             sfibI(k), sfibI(k - 1), sfibI(k - 2));
    if (abs(k) < 36 || args.length > 2)
        // set a limit for recursive version
        writefln("R : %20d <- %20d + %20d",
                 sfibR(k), sfibM(k - 1), sfibM(k - 2));
    writefln("O : %20d <- %20d + %20d",
             sfibM(k), sfibM(k - 1), sfibM(k - 2));
    foreach (i, f; fibG(-9))
        writef("%d:%d | ", i, f);
}

The code includes four versions of functions to calculate the nth Fibonacci number, supporting both positive and negative inputs. The traditional recursive approach is optimized with static storage for intermediate results. The functions have a limit of 84 for FibD due to floating point precision, and 92 for the others due to long overflow. The code performs faster than the matrix exponentiation version for large inputs.


void main() {
    import std.algorithm: filter, equal;

    immutable data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    auto evens = data.filter!(x => x % 2 == 0); // Lazy.
    assert(evens.equal([2, 4, 6, 8, 10]));
}

Library: Tango
import tango.core.Array, tango.io.Stdout;

void main() {
    auto array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    // removeIf places even elements at the beginnig of the array and returns number of found evens
    auto evens = array.removeIf( ( typeof(array[0]) i ) { return (i % 2) == 1; } );
    Stdout("Evens - ")( array[0 .. evens] ).newline; // The order of even elements is preserved
    Stdout("Odds - ")( array[evens .. $].sort ).newline; // Unlike odd elements
}

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: D version 2
import std.stdio, std.string;

void main() {
    const s = "the quick brown fox jumps over the lazy dog";
    enum n = 5, m = 3;

    writeln(s[n .. n + m]);

    writeln(s[n .. $]);

    writeln(s[0 .. $ - 1]);

    const i = s.indexOf("q");
    writeln(s[i .. i + m]);

    const j = s.indexOf("qu");
    writeln(s[j .. j + 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.


void main() {
	import std.range, std.conv;

	string s1 = "hello"; // UTF-8
	assert(s1.retro.text == "olleh");

	wstring s2 = "hello"w; // UTF-16
	assert(s2.retro.wtext == "olleh"w);

	dstring s3 = "hello"d; // UTF-32
	assert(s3.retro.dtext == "olleh"d);

	// without using std.range:
	dstring s4 = "hello"d;
	assert(s4.dup.reverse == "olleh"d); // simple but inefficient (copies first, then reverses)
}

Reverses a given string while preserving Unicode combining characters. For instance, it transforms "asdf" to "fdsa" and "as⃝df̅" to "f̅ds⃝a".


import std.stdio, std.array, std.algorithm, std.range, std.ascii,
       std.conv, std.string, std.regex, std.typecons;

string unique(in string s) pure nothrow @safe {
    string result;
    foreach (immutable char c; s)
        if (!result.representation.canFind(c)) // Assumes ASCII string.
            result ~= c;
    return result;
}

struct Playfair {
    string from, to;
    string[string] enc, dec;

    this(in string key, in string from_ = "J", in string to_ = null)
    pure /*nothrow @safe*/ {
        this.from = from_;
        if (to_.empty)
            this.to = (from_ == "J") ? "I" : "";

        immutable m = _canonicalize(key ~ uppercase)
                      .unique
                      .chunks(5)
                      .map!text
                      .array;
        auto I5 = 5.iota;

        foreach (immutable R; m)
            foreach (immutable i, immutable j; cartesianProduct(I5, I5))
                if (i != j)
                    enc[[R[i], R[j]]] = [R[(i + 1) % 5], R[(j+1) % 5]];

        foreach (immutable r; I5) {
            immutable c = m.transversal(r).array;
            foreach (immutable i, immutable j; cartesianProduct(I5, I5))
                if (i != j)
                    enc[[c[i], c[j]]] = [c[(i + 1) % 5], c[(j+1) % 5]];
        }

        foreach (i1, j1, i2, j2; cartesianProduct(I5, I5, I5, I5))
            if (i1 != i2 && j1 != j2)
                enc[[m[i1][j1], m[i2][j2]]] = [m[i1][j2], m[i2][j1]];

        dec = enc.byKeyValue.map!(t => tuple(t.value, t.key)).assocArray;
    }

    private string _canonicalize(in string s) const pure @safe {
        return s.toUpper.removechars("^A-Z").replace(from, to);
    }

    string encode(in string s) const /*pure @safe*/ {
        return _canonicalize(s)
               .matchAll(r"(.)(?:(?!\1)(.))?")
               .map!(m => enc[m[0].leftJustify(2, 'X')])
               .join(' ');
    }

    string decode(in string s) const pure @safe {
        return _canonicalize(s).chunks(2).map!(p => dec[p.text]).join(' ');
    }
}

void main() /*@safe*/ {
    /*immutable*/ const pf = Playfair("Playfair example");
    immutable orig = "Hide the gold in...the TREESTUMP!!!";
    writeln("Original: ", orig);
    immutable enc = pf.encode(orig);
    writeln(" Encoded: ", enc);
    writeln(" Decoded: ", pf.decode(enc));
}

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.


import std.stdio, std.typecons, std.algorithm, std.container;

alias Vertex = string;
alias Weight = int;

struct Neighbor {
    Vertex target;
    Weight weight;
}

alias AdjacencyMap = Neighbor[][Vertex];

pure dijkstraComputePaths(Vertex source, Vertex target, AdjacencyMap adjacencyMap){
    Weight[Vertex] minDistance;
    Vertex[Vertex] previous;

    foreach(v, neighs; adjacencyMap){
        minDistance[v] = Weight.max;
        foreach(n; neighs) minDistance[n.target] = Weight.max;
    }

    minDistance[source] = 0;
    auto vertexQueue = redBlackTree(tuple(minDistance[source], source));

    foreach(_, u; vertexQueue){
        if (u == target)
            break;

        // Visit each edge exiting u.
        foreach(n; adjacencyMap.get(u, null)){
            const v = n.target;
            const distanceThroughU = minDistance[u] + n.weight;
            if(distanceThroughU < minDistance[v]){
                vertexQueue.removeKey(tuple(minDistance[v], v));
                minDistance[v] = distanceThroughU;
                previous[v] = u;
                vertexQueue.insert(tuple(minDistance[v], v));
            }
        }
    }

    return tuple(minDistance, previous);
}

pure dijkstraGetShortestPathTo(Vertex v, Vertex[Vertex] previous){
    Vertex[] path = [v];

    while (v in previous) {
        v = previous[v];
        if (v == path[$ - 1])
            break;
        path ~= v;
    }

    path.reverse();
    return path;
}

void main() {
    immutable arcs = [tuple("a", "b", 7),
                      tuple("a", "c", 9),
                      tuple("a", "f", 14),
                      tuple("b", "c", 10),
                      tuple("b", "d", 15),
                      tuple("c", "d", 11),
                      tuple("c", "f", 2),
                      tuple("d", "e", 6),
                      tuple("e", "f", 9)];

    AdjacencyMap adj;
    foreach (immutable arc; arcs) {
        adj[arc[0]] ~= Neighbor(arc[1], arc[2]);
        // Add this if you want an undirected graph:
        //adj[arc[1]] ~= Neighbor(arc[0], arc[2]);
    }

    const minDist_prev = dijkstraComputePaths("a", "e", adj);
    const minDistance = minDist_prev[0];
    const previous = minDist_prev[1];

    writeln(`Distance from "a" to "e": `, minDistance["e"]);
    writeln("Path: ", dijkstraGetShortestPathTo("e", previous));
}

Implement Dijkstra's algorithm to find the shortest path from a single source to all other vertices in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges depicting the shortest path to each reachable node from the start node. The program also interprets the output to display the shortest path from the start node to specific nodes.


import std.stdio, std.algorithm;

class AVLtree {
    private Node* root;

    private static struct Node {
        private int key, balance;
        private Node* left, right, parent;

        this(in int k, Node* p) pure nothrow @safe @nogc {
            key = k;
            parent = p;
        }
    }

    public bool insert(in int key) pure nothrow @safe {
        if (root is null)
            root = new Node(key, null);
        else {
            Node* n = root;
            Node* parent;
            while (true) {
                if (n.key == key)
                    return false;

                parent = n;

                bool goLeft = n.key > key;
                n = goLeft ? n.left : n.right;

                if (n is null) {
                    if (goLeft) {
                        parent.left = new Node(key, parent);
                    } else {
                        parent.right = new Node(key, parent);
                    }
                    rebalance(parent);
                    break;
                }
            }
        }
        return true;
    }

    public void deleteKey(in int delKey) pure nothrow @safe @nogc {
        if (root is null)
            return;
        Node* n = root;
        Node* parent = root;
        Node* delNode = null;
        Node* child = root;

        while (child !is null) {
            parent = n;
            n = child;
            child = delKey >= n.key ? n.right : n.left;
            if (delKey == n.key)
                delNode = n;
        }

        if (delNode !is null) {
            delNode.key = n.key;

            child = n.left !is null ? n.left : n.right;

            if (root.key == delKey) {
                root = child;
            } else {
                if (parent.left is n) {
                    parent.left = child;
                } else {
                    parent.right = child;
                }
                rebalance(parent);
            }
        }
    }

    private void rebalance(Node* n) pure nothrow @safe @nogc {
        setBalance(n);

        if (n.balance == -2) {
            if (height(n.left.left) >= height(n.left.right))
                n = rotateRight(n);
            else
                n = rotateLeftThenRight(n);

        } else if (n.balance == 2) {
            if (height(n.right.right) >= height(n.right.left))
                n = rotateLeft(n);
            else
                n = rotateRightThenLeft(n);
        }

        if (n.parent !is null) {
            rebalance(n.parent);
        } else {
            root = n;
        }
    }

    private Node* rotateLeft(Node* a) pure nothrow @safe @nogc {
        Node* b = a.right;
        b.parent = a.parent;

        a.right = b.left;

        if (a.right !is null)
            a.right.parent = a;

        b.left = a;
        a.parent = b;

        if (b.parent !is null) {
            if (b.parent.right is a) {
                b.parent.right = b;
            } else {
                b.parent.left = b;
            }
        }

        setBalance(a, b);

        return b;
    }

    private Node* rotateRight(Node* a) pure nothrow @safe @nogc {
        Node* b = a.left;
        b.parent = a.parent;

        a.left = b.right;

        if (a.left !is null)
            a.left.parent = a;

        b.right = a;
        a.parent = b;

        if (b.parent !is null) {
            if (b.parent.right is a) {
                b.parent.right = b;
            } else {
                b.parent.left = b;
            }
        }

        setBalance(a, b);

        return b;
    }

    private Node* rotateLeftThenRight(Node* n) pure nothrow @safe @nogc {
        n.left = rotateLeft(n.left);
        return rotateRight(n);
    }

    private Node* rotateRightThenLeft(Node* n) pure nothrow @safe @nogc {
        n.right = rotateRight(n.right);
        return rotateLeft(n);
    }

    private int height(in Node* n) const pure nothrow @safe @nogc {
        if (n is null)
            return -1;
        return 1 + max(height(n.left), height(n.right));
    }

    private void setBalance(Node*[] nodes...) pure nothrow @safe @nogc {
        foreach (n; nodes)
            n.balance = height(n.right) - height(n.left);
    }

    public void printBalance() const @safe {
        printBalance(root);
    }

    private void printBalance(in Node* n) const @safe {
        if (n !is null) {
            printBalance(n.left);
            write(n.balance, ' ');
            printBalance(n.right);
        }
    }
}

void main() @safe {
    auto tree = new AVLtree();

    writeln("Inserting values 1 to 10");
    foreach (immutable i; 1 .. 11)
        tree.insert(i);

    write("Printing balance: ");
    tree.printBalance;
}

implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.


import std.stdio, std.typecons, std.math;

class ValueException : Exception {
    this(string msg_) pure { super(msg_); }
}

struct V2 { double x, y; }
struct Circle { double x, y, r; }

/**Following explanation at:
http://mathforum.org/library/drmath/view/53027.html
*/
Tuple!(Circle, Circle)
circlesFromTwoPointsAndRadius(in V2 p1, in V2 p2, in double r)
pure in {
    assert(r >= 0, "radius can't be negative");
} body {
    enum nBits = 40;

    if (r.abs < (1.0 / (2.0 ^^ nBits)))
        throw new ValueException("radius of zero");

    if (feqrel(p1.x, p2.x) >= nBits &&
        feqrel(p1.y, p2.y) >= nBits)
        throw new ValueException("coincident points give" ~
                                 " infinite number of Circles");

    // Delta between points.
    immutable d = V2(p2.x - p1.x, p2.y - p1.y);

    // Distance between points.
    immutable q = sqrt(d.x ^^ 2 + d.y ^^ 2);
    if (q > 2.0 * r)
        throw new ValueException("separation of points > diameter");

    // Halfway point.
    immutable h = V2((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);

    // Distance along the mirror line.
    immutable dm = sqrt(r ^^ 2 - (q / 2) ^^ 2);

    return typeof(return)(
        Circle(h.x - dm * d.y / q, h.y + dm * d.x / q, r.abs),
        Circle(h.x + dm * d.y / q, h.y - dm * d.x / q, r.abs));
}

void main() {
    foreach (immutable t; [
                 tuple(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 2.0),
                 tuple(V2(0.0000, 2.0000), V2(0.0000, 0.0000), 1.0),
                 tuple(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 2.0),
                 tuple(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 0.5),
                 tuple(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 0.0)]) {
        writefln("Through points:\n  %s   %s  and radius %f\n" ~
                 "You can construct the following circles:", t[]);
        try {
            writefln("  %s\n  %s\n",
                     circlesFromTwoPointsAndRadius(t[])[]);
        } catch (ValueException v)
            writefln("  ERROR: %s\n", v.msg);
    }
}

"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned."


import std.stdio, std.range, std.algorithm;

/// Rotate uint left.
uint rol(in uint x, in uint nBits) @safe pure nothrow @nogc {
    return (x << nBits) | (x >> (32 - nBits));
}

alias Nibble = ubyte; // 4 bits used.
alias SBox = immutable Nibble[16][8];

private bool _validateSBox(in SBox data) @safe pure nothrow @nogc {
    foreach (const ref row; data)
        foreach (ub; row)
            if (ub >= 16) // Verify it's a nibble.
                return false;
    return true;
}

struct GOST(s...) if (s.length == 1 && s[0]._validateSBox) {
    private static generate(ubyte k)() @safe pure nothrow {
        return k87.length.iota
               .map!(i=> (s[0][k][i >> 4] << 4) | s[0][k - 1][i & 0xF])
               .array;
    }

    private uint[2] buffer;
    private static immutable ubyte[256] k87 = generate!7,
                                        k65 = generate!5,
                                        k43 = generate!3,
                                        k21 = generate!1;

    // Endianess problems?
    private static uint f(in uint x) pure nothrow @nogc @safe {
        immutable uint y = (k87[(x >> 24) & 0xFF] << 24) |
                           (k65[(x >> 16) & 0xFF] << 16) |
                           (k43[(x >>  8) & 0xFF] <<  8) |
                            k21[ x        & 0xFF];
        return rol(y, 11);
    }

    // This performs only a step of the encoding.
    public void mainStep(in uint[2] input, in uint key)
    pure nothrow @nogc @safe {
        buffer[0] = f(key + input[0]) ^ input[1];
        buffer[1] = input[0];
    }
}

void main() {
    // S-boxes used by the Central Bank of Russian Federation:
    // http://en.wikipedia.org/wiki/GOST_28147-89
    // (This is a matrix of nibbles).
    enum SBox cbrf = [
      [ 4, 10,  9,  2, 13,  8,  0, 14,  6, 11,  1, 12,  7, 15,  5,  3],
      [14, 11,  4, 12,  6, 13, 15, 10,  2,  3,  8,  1,  0,  7,  5,  9],
      [ 5,  8,  1, 13, 10,  3,  4,  2, 14, 15, 12,  7,  6,  0,  9, 11],
      [ 7, 13, 10,  1,  0,  8,  9, 15, 14,  4,  6, 12, 11,  2,  5,  3],
      [ 6, 12,  7,  1,  5, 15, 13,  8,  4, 10,  9, 14,  0,  3, 11,  2],
      [ 4, 11, 10,  0,  7,  2,  1, 13,  3,  6,  8,  5,  9, 12, 15, 14],
      [13, 11,  4,  1,  3, 15,  5,  9,  0, 10, 14,  7,  6,  8,  2, 12],
      [ 1, 15, 13,  0,  5,  7, 10,  4,  9,  2,  3, 14,  6, 11,  8, 12]];

    GOST!cbrf g;

    // Example from the talk page (bytes swapped for endianess):
    immutable uint[2] input = [0x_04_3B_04_21, 0x_04_32_04_30];
    immutable uint key = 0x_E2_C1_04_F9;

    g.mainStep(input, key);
    writefln("%(%08X %)", g.buffer);
}

Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.


import std.stdio, std.random;

void main() {
    while (true) {
        int r = uniform(0, 20);
        write(r, " ");
        if (r == 10)
            break;
        write(uniform(0, 20), " ");
    }
}

generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.


import std.stdio, std.math, std.traits;

ulong mersenneFactor(in ulong p) pure nothrow @nogc {
    static bool isPrime(T)(in T n) pure nothrow @nogc {
        if (n < 2 || n % 2 == 0)
            return n == 2;
        for (Unqual!T i = 3; i ^^ 2 <= n; i += 2)
            if (n % i == 0)
                return false;
        return true;
    }

    static ulong modPow(in ulong cb, in ulong ce,in ulong m)
    pure nothrow @nogc {
        ulong b = cb;
        ulong result = 1;
        for (ulong e = ce; e > 0; e >>= 1) {
            if ((e & 1) == 1)
                result = (result * b) % m;
            b = (b ^^ 2) % m;
        }
        return result;
    }

    immutable ulong limit = p <= 64 ? cast(ulong)(real(2.0) ^^ p - 1).sqrt : uint.max; // prevents silent overflows
    for (ulong k = 1; (2 * p * k + 1) < limit; k++) {
        immutable ulong q = 2 * p * k + 1;
        if ((q % 8 == 1 || q % 8 == 7) && isPrime(q) &&
            modPow(2, p, q) == 1)
            return q;
    }
    return 1; // returns a sensible smallest factor
}

void main() {
    writefln("Factor of M929: %d", 929.mersenneFactor);
}

implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.


Library: KXML
import kxml.xml;
char[]xmlinput =
"<inventory title=\"OmniCorp Store #45x10^3\">

    <item upc=\"123456789\" stock=\"12\">
      <name>Invisibility Cream</name>
      <price>14.50</price>
      <description>Makes you invisible</description>
    </item>
    <item upc=\"445322344\" stock=\"18\">
      <name>Levitation Salve</name>
      <price>23.99</price>
      <description>Levitate yourself for up to 3 hours per application</description>
    </item>

    <item upc=\"485672034\" stock=\"653\">
      <name>Blork and Freen Instameal</name>
      <price>4.95</price>
      <description>A tasty meal in a tablet; just add water</description>
    </item>
    <item upc=\"132957764\" stock=\"44\">
      <name>Grob winglets</name>
      <price>3.56</price>
      <description>Tender winglets of Grob. Just add water</description>
    </item>

</inventory>
";
void main() {
        auto root = readDocument(xmlinput);
        auto firstitem = root.parseXPath("inventory/section/item")[0];
        foreach(price;root.parseXPath("inventory/section/item/price")) {
                std.stdio.writefln("%s",price.getCData);
        }
        auto namearray = root.parseXPath("inventory/section/item/name");
}

The code retrieves the first "item" element, prints out each "price" element, and creates an array of all the "name" elements from an XML document representing an inventory of OmniCorp Store. Note that the KXML library used for this task has limited XPath support.


void main() {
    import std.stdio, std.algorithm, std.range;

    // Not true sets, items can be repeated, but must be sorted.
    auto s1 = [1, 2, 3, 4, 5, 6].assumeSorted;
    auto s2 = [2, 5, 6, 3, 4, 8].sort(); // [2,3,4,5,6,8].
    auto s3 = [1, 2, 5].assumeSorted;

    assert(s1.canFind(4)); // Linear search.
    assert(s1.contains(4)); // Binary search.
    assert(s1.setUnion(s2).equal([1,2,2,3,3,4,4,5,5,6,6,8]));
    assert(s1.setIntersection(s2).equal([2, 3, 4, 5, 6]));
    assert(s1.setDifference(s2).equal([1]));
    assert(s1.setSymmetricDifference(s2).equal([1, 8]));
    assert(s3.setDifference(s1).empty); // It's a subset.
    assert(!s1.equal(s2));

    auto s4 = [[1, 4, 7, 8], [1, 7], [1, 7, 8], [4], [7]];
    const s5 = [1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8];
    assert(s4.nWayUnion.equal(s5));
}
 ==D==
module set;
import std.typecons : Tuple, tuple;
struct Set(V) { // Limited set of V-type elements                                        // here 'this' is named A, s is B, v V-type item

protected V[] array;

	this(const Set s) {                                                              // construct A by copy of B
		array = s.array.dup;
	}

	this(V[] arg...){                                                                // construct A with items
		foreach(v; arg) if (v.isNotIn(array)) array ~= v;
	}

	enum : Set { empty = Set() }                                                     // ∅

	ref Set opAssign()(const Set s) {                                                // A = B
		array = s.array.dup;
		return this;
	}

	bool opBinaryRight(string op : "in")(const V v) const {                          // v ∈ A
		return v.isIn(array);
	}

	ref Set opOpAssign(string op)(const V v) if (op == "+" || op == "|") {           // A += {v}          // + = ∪ = |
		if (v.isIn(array)) return this;
		array ~= v;
		return this;
	}

	ref Set opOpAssign(string op)(const Set s) if (op == "+" || op == "|") {         // A += B
		foreach(x; s.array) if (x.isNotIn(array)) array ~= x;
		return this;
	}

	Set opBinary(string op)(const V v) const if (op == "+" || op == "|"){            // A + {v}
		Set result = this;
		result += v;
		return result;
	}

	Set opBinaryRight(string op)(const V v) const if (op == "+" || op == "|") {      // {v} + A
		Set result = this;
		result += v;
		return result;
	}

	Set opBinary(string op)(const Set s) const if (op == "+" || op == "|") {         // A + B
		Set result = this;
		result += s;
		return result;
	}

	Set opBinary(string op : "&")(const Set s) const{                                // A ∩ B               // ∩ = &
		Set result;
		foreach(x; array) if(x.isIn(s.array)) result += x;
		return result;
	}

	ref Set opOpAssign(string op : "&")(const Set s) {                               // A ∩= B
		return this(this & s);
	}

	Set opBinary(string op : "^")(const Set s) const {                               // (A ∪ B) - (A ∩ B)    //  = A ^ B
		Set result;
		foreach(x; array) if (x.isNotIn(s.array)) result += x;
		foreach(x; s.array) if(x.isNotIn(array)) result += x;
		return result;
	}

	ref opOpAssign(string op : "^")(const Set s) {
		return this = this ^ s;
	}

	Set opBinary(string op : "-")(const Set s) const {                                // A - B
		Set r;
		foreach(x; array) if(x.isNot(s.array)) r += x;
		return r;
	}

	ref Set opOpAssign(string op : "-")(const Set s) {                                // A -= B
		return this = this - s;
	}

	Set!(Tuple!(V,U)) opBinary(U, string op : "*")(const Set!U s) const {             // A × B = { (x, y) | ∀x ∈ A ∧ ∀y ∈ B }
		Set!(Tuple!(V, U)) r;
		foreach(x; array) foreach(y; s.array) r += tuple(x, y);
		return r;
	}

	bool isEmpty() const { return !array.length;}                                     // A ≟ ∅

	bool opBinary(string op : "in")(const Set s) const {                              // A ⊂ s
		foreach(v; array) if(v.isNotIn(s.array)) return false;
		return true;
	}

	bool opEquals(const Set s) const {                                                // A ≟ B
		if (array.length != s.array.length) return false;
		return this in s;
	}

	T[] array() const @property { return array.dup;}

}

Set!(Tuple!(T, T)) sqr(T)(const Set!T s) { return s * s; }                                 // A²

auto pow(T, uint n : 0)(const Set!T s) {                                                   // A ^ 0
	return Set!T.empty;
}

auto pow(T, uint n : 1)(const Set!T s) {                                                   // A ^ 1 = A
	return s;
}

auto pow(T, uint n : 2)(const Set!T s) {                                                   // A ^ 2 (=A²)
	return sqr!T(s);
}

auto pow(T, uint n)(const Set!T s) if(n % 2) {                                             // if n Odd,  A^n = A * (A^(n/2))²
        return s * sqr!T(pow!(T, n/2)(s));
}

auto pow(T, uint n)(const Set!T s) if(!(n % 2)) {                                           // if n Even, A^n = (A^(n/2))²
	return sqr!T(pow!(T, n/2)(s));
}

size_t Card(T)(const Set!T s) {return s.length; }                                           // Card(A)

Set!(Set!T) power(T)(Set!T s) {                                                             // ∀B ∈ P(A) ⇒ B ⊂ A
	Set!(Set!T) ret;
	foreach(e; s.array) {
		Set!(Set!T) rs;
		foreach(x; ret.array) {
			x += e;
			rs += x;
		}
		ret += rs;
	}
	return ret;
}

bool isIn(T)(T x, T[] array){
	foreach(a; array) if(a == x) return true;
	return false;
}
bool isNotIn(T)(T x, T[] array){
	foreachj(a; array) if(a == x) return false;
	return 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.


void main() {
    import std.stdio, std.range, std.algorithm, std.datetime;

    writeln("Christmas comes on a Sunday in the years:\n",
            iota(2008, 2122)
            .filter!(y => Date(y, 12, 25).dayOfWeek == DayOfWeek.sun));
}

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.


import std.stdio, std.math, std.algorithm, std.traits,
       std.typecons, std.numeric, std.range, std.conv;

template elementwiseMat(string op) {
    T[][] elementwiseMat(T)(in T[][] A, in T B) pure nothrow {
        if (A.empty)
            return null;
        auto R = new typeof(return)(A.length, A[0].length);
        foreach (immutable r, const row; A)
            R[r][] = mixin("row[] " ~ op ~ "B");
        return R;
    }

    T[][] elementwiseMat(T, U)(in T[][] A, in U[][] B)
    pure nothrow if (is(Unqual!T == Unqual!U)) {
        assert(A.length == B.length);
        if (A.empty)
            return null;
        auto R = new typeof(return)(A.length, A[0].length);
        foreach (immutable r, const row; A) {
            assert(row.length == B[r].length);
            R[r][] = mixin("row[] " ~ op ~ "B[r][]");
        }
        return R;
    }
}

alias mSum = elementwiseMat!q{ + },
      mSub = elementwiseMat!q{ - },
      pMul = elementwiseMat!q{ * },
      pDiv = elementwiseMat!q{ / };

bool isRectangular(T)(in T[][] mat) pure nothrow {
    return mat.all!(r => r.length == mat[0].length);
}

T[][] matMul(T)(in T[][] a, in T[][] b) pure nothrow
in {
    assert(a.isRectangular && b.isRectangular &&
           a[0].length == b.length);
} body {
    auto result = new T[][](a.length, b[0].length);
    auto aux = new T[b.length];
    foreach (immutable j; 0 .. b[0].length) {
        foreach (immutable k; 0 .. b.length)
            aux[k] = b[k][j];
        foreach (immutable i; 0 .. a.length)
            result[i][j] = a[i].dotProduct(aux);
    }
    return result;
}

Unqual!T[][] transpose(T)(in T[][] m) pure nothrow {
    auto r = new Unqual!T[][](m[0].length, m.length);
    foreach (immutable nr, row; m)
        foreach (immutable nc, immutable c; row)
            r[nc][nr] = c;
    return r;
}

T norm(T)(in T[][] m) pure nothrow {
    return transversal(m, 0).map!q{ a ^^ 2 }.sum.sqrt;
}

Unqual!T[][] makeUnitVector(T)(in size_t dim) pure nothrow {
    auto result = new Unqual!T[][](dim, 1);
    foreach (row; result)
        row[] = 0;
    result[0][0] = 1;
    return result;
}

/// Return a nxn identity matrix.
Unqual!T[][] matId(T)(in size_t n) pure nothrow {
    auto Id = new Unqual!T[][](n, n);
    foreach (immutable r, row; Id) {
        row[] = 0;
        row[r] = 1;
    }
    return Id;
}

T[][] slice2D(T)(in T[][] A,
                 in size_t ma, in size_t mb,
                 in size_t na, in size_t nb) pure nothrow {
    auto B = new T[][](mb - ma + 1, nb - na + 1);
    foreach (immutable i, brow; B)
        brow[] = A[ma + i][na .. na + brow.length];
    return B;
}

size_t rows(T)(in T[][] A) pure nothrow { return A.length; }

size_t cols(T)(in T[][] A) pure nothrow {
    return A.length ? A[0].length : 0;
}

T[][] mcol(T)(in T[][] A, in size_t n) pure nothrow {
    return slice2D(A, 0, A.rows - 1, n, n);
}

T[][] matEmbed(T)(in T[][] A, in T[][] B,
                  in size_t row, in size_t col) pure nothrow {
    auto C = new T[][](rows(A), cols(A));
    foreach (immutable i, const arow; A)
        C[i][] = arow[]; // Some wasted copies.
    foreach (immutable i, const brow; B)
        C[row + i][col .. col + brow.length] = brow[];
    return C;
}

// Main routines ---------------

T[][] makeHouseholder(T)(in T[][] a) {
    immutable m = a.rows;
    immutable T s = a[0][0].sgn;
    immutable e = makeUnitVector!T(m);
    immutable u = mSum(a, pMul(e, a.norm * s));
    immutable v = pDiv(u, u[0][0]);
    immutable beta = 2.0 / v.transpose.matMul(v)[0][0];
    return mSub(matId!T(m), pMul(v.matMul(v.transpose), beta));
}

Tuple!(T[][],"Q", T[][],"R") QRdecomposition(T)(T[][] A) {
    immutable m = A.rows;
    immutable n = A.cols;
    auto Q = matId!T(m);

    // Work on n columns of A.
    foreach (immutable i; 0 .. (m == n ? n - 1 : n)) {
        // Select the i-th submatrix. For i=0 this means the original
        // matrix A.
        immutable B = slice2D(A, i, m - 1, i, n - 1);

        // Take the first column of the current submatrix B.
        immutable x = mcol(B, 0);

        // Create the Householder matrix for the column and embed it
        // into an mxm identity.
        immutable H = matEmbed(matId!T(m), x.makeHouseholder, i, i);

        // The product of all H matrices from the right hand side is
        // the orthogonal matrix Q.
        Q = Q.matMul(H);

        // The product of all H matrices with A from the LHS is the
        // upper triangular matrix R.
        A  = H.matMul(A);
    }

    // Return Q and R.
    return typeof(return)(Q, A);
}

// Polynomial regression ---------------

/// Solve an upper triangular system by back substitution.
T[][] solveUpperTriangular(T)(in T[][] R, in T[][] b) pure nothrow {
    immutable n = R.cols;
    auto x = new T[][](n, 1);

    foreach_reverse (immutable k; 0 .. n) {
        T tot = 0;
        foreach (immutable j; k + 1 .. n)
            tot += R[k][j] * x[j][0];
        x[k][0] = (b[k][0] - tot) / R[k][k];
    }

    return x;
}

/// Solve a linear least squares problem by QR decomposition.
T[][] lsqr(T)(T[][] A, in T[][] b) pure nothrow {
    const qr = A.QRdecomposition;
    immutable n = qr.R.cols;
    return solveUpperTriangular(
        slice2D(qr.R, 0, n - 1, 0, n - 1),
        slice2D(qr.Q.transpose.matMul(b), 0, n - 1, 0, 0));
}

T[][] polyFit(T)(in T[][] x, in T[][] y, in size_t n) pure nothrow {
    immutable size_t m = x.cols;
    auto A = new T[][](m, n + 1);
    foreach (immutable i, row; A)
        foreach (immutable j, ref item; row)
            item = x[0][i] ^^ j;
    return lsqr(A, y.transpose);
}

void main() {
    // immutable (Q, R) = QRdecomposition([[12.0, -51,   4],
    immutable qr = QRdecomposition([[12.0, -51,   4],
                                    [ 6.0, 167, -68],
                                    [-4.0,  24, -41]]);
    immutable form = "[%([%(%2.3f, %)]%|,\n %)]\n";
    writefln(form, qr.Q);
    writefln(form, qr.R);

    immutable x = [[0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]];
    immutable y = [[1.0, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]];
    polyFit(x, y, 2).writeln;
}

The code performs QR decomposition on a given matrix using the Householder reflections method. It decomposes the matrix into an orthogonal matrix and an upper triangular matrix. It also demonstrates the use of QR decomposition for solving linear least squares problems. The code handles cases where the matrix is not square by cutting off zero padded bottom rows. The final solution is obtained by back substitution. The code utilizes functions from Element-wise_operations, Matrix multiplication, and Matrix transposition.


void main() {
    import std.stdio, std.algorithm;

    [1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2]
    .sort()
    .uniq
    .writeln;
}

implement three methods to remove duplicate elements from an array: 1) using a hash table, 2) sorting the elements and removing consecutive duplicates, and 3) iterating through the list and discarding any repeated elements. An additional method using an associative array is also implemented.


import std.stdio : writefln, writeln;
import std.algorithm: filter;
import std.array;

T[] quickSort(T)(T[] xs) =>
  xs.length == 0 ? [] :
    xs[1 .. $].filter!(x => x< xs[0]).array.quickSort ~
    xs[0 .. 1] ~
    xs[1 .. $].filter!(x => x>=xs[0]).array.quickSort;

void main() =>
  [4, 65, 2, -31, 0, 99, 2, 83, 782, 1].quickSort.writeln;

implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by selecting 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 code includes two versions of the algorithm, one that creates new arrays for the partitions and another more efficient one that sorts the array in place by swapping elements. The pivot selection method is not specified.


Works with: D version DMD 1.026
Library: Tango
module datetimedemo ;

import tango.time.Time ;
import tango.text.locale.Locale ;
import tango.time.chrono.Gregorian ;

import tango.io.Stdout ;

void main() {
    Gregorian g = new Gregorian ;
    Stdout.layout = new Locale; // enable Stdout to handle date/time format
    Time d = g.toTime(2007, 11, 10, 0, 0, 0, 0, g.AD_ERA) ;
    Stdout.format("{:yyy-MM-dd}", d).newline ;
    Stdout.format("{:dddd, MMMM d, yyy}", d).newline ;
    d = g.toTime(2008, 2, 1, 0, 0, 0, 0, g.AD_ERA) ;
    Stdout.format("{:dddd, MMMM d, yyy}", d).newline ;
}

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


import std.algorithm;
import std.range;

auto powerSet(R)(R r)
{
	return
		(1L<<r.length)
		.iota
		.map!(i =>
			r.enumerate
			.filter!(t => (1<<t[0]) & i)
			.map!(t => t[1])
		);
}

unittest
{
	int[] emptyArr;
	assert(emptyArr.powerSet.equal!equal([emptyArr]));
	assert(emptyArr.powerSet.powerSet.equal!(equal!equal)([[], [emptyArr]]));
}

void main(string[] args)
{
	import std.stdio;
	args[1..$].powerSet.each!writeln;
}

import std.range;

struct PowerSet(R)
	if (isRandomAccessRange!R)
{
	R r;
	size_t position;

	struct PowerSetItem
	{
		R r;
		size_t position;

		private void advance()
		{
			while (!(position & 1))
			{
				r.popFront();
				position >>= 1;
			}
		}

		@property bool empty() { return position == 0; }
		@property auto front()
		{
			advance();
			return r.front;
		}
		void popFront()
		{
			advance();
			r.popFront();
			position >>= 1;
		}
	}

	@property bool empty() { return position == (1 << r.length); }
	@property PowerSetItem front() { return PowerSetItem(r.save, position); }
	void popFront() { position++; }
}

auto powerSet(R)(R r) { return PowerSet!R(r); }

The code takes a set S as input and generates its power set. The power set includes all possible subsets of S, including the empty set and the set itself. For a set with n elements, the power set will have 2^n elements. The code also demonstrates the ability to handle edge cases such as the power set of an empty set and the power set of a set containing only the empty set. The implementation uses a lazy enumeration approach to generate the power set.


string toRoman(int n) pure nothrow
in {
    assert(n < 5000);
} body {
    static immutable weights = [1000, 900, 500, 400, 100, 90,
                                50, 40, 10, 9, 5, 4, 1];
    static immutable symbols = ["M","CM","D","CD","C","XC","L",
                                "XL","X","IX","V","IV","I"];

    string roman;
    foreach (i, w; weights) {
        while (n >= w) {
            roman ~= symbols[i];
            n -= w;
        }
        if (n == 0)
            break;
    }
    return roman;
} unittest {
    assert(toRoman(455)  == "CDLV");
    assert(toRoman(3456) == "MMMCDLVI");
    assert(toRoman(2488) == "MMCDLXXXVIII");
}

void main() {}

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


// All D arrays are capable of bounds checks.

import std.stdio, core.stdc.stdlib;
import std.container: Array;

void main() {
    // GC-managed heap allocated dynamic array:
    auto array1 = new int[1];
    array1[0] = 1;
    array1 ~= 3; // append a second item
    // array1[10] = 4; // run-time error
    writeln("A) Element 0: ", array1[0]);
    writeln("A) Element 1: ", array1[1]);

    // Stack-allocated fixed-size array:
    int[5] array2;
    array2[0] = 1;
    array2[1] = 3;
    // array2[2] = 4; // compile-time error
    writeln("B) Element 0: ", array2[0]);
    writeln("B) Element 1: ", array2[1]);

    // Stack-allocated dynamic fixed-sized array,
    // length known only at run-time:
    int n = 2;
    int[] array3 = (cast(int*)alloca(n * int.sizeof))[0 .. n];
    array3[0] = 1;
    array3[1] = 3;
    // array3[10] = 4; // run-time error
    writeln("C) Element 0: ", array3[0]);
    writeln("C) Element 1: ", array3[1]);

    // Phobos-defined  heap allocated not GC-managed array:
    Array!int array4;
    array4.length = 2;
    array4[0] = 1;
    array4[1] = 3;
    // array4[10] = 4; // run-time exception
    writeln("D) Element 0: ", array4[0]);
    writeln("D) Element 1: ", array4[1]);
}

demonstrate the basic syntax of creating an array, assigning a value to it, and retrieving an element in a specific programming language. It includes both fixed-length and dynamic arrays, and shows how to push a value into the array.


Library: Phobos
Works with: D version 2
import std.file: copy;

void main() {
    copy("input.txt", "output.txt");
}

void main() {
import std.file;
auto data = std.file.read("input.txt");
std.file.write("output.txt", data);
}

import std.stdio;

int main() {
    auto from = File("input.txt", "rb");
    scope(exit) from.close();

    auto to = File("output.txt", "wb");
    scope(exit) to.close();

    foreach(buffer; from.byChunk(new ubyte[4096*1024])) {
        to.rawWrite(buffer);
    }

    return 0;
}

Library: Tango
Works with: D version 1

import tango.io.device.File;

void main()
{
    auto from = new File("input.txt");
    auto to = new File("output.txt", File.WriteCreate);
    to.copy(from).close;
    from.close;
}

import tango.io.device.File;

void main()
{
    auto to = new File("output.txt", File.WriteCreate);
    to.copy(new File("input.txt")).close;
}

demonstrate how to read content from an input file into an intermediate variable and then write this content into an output file. Exception handling is managed by Tango. The codes also include a shorter example where the output file is not explicitly closed.


void main() {
    import std.stdio, std.string;

    immutable s = "alphaBETA";
    s.toUpper.writeln;
    s.toLower.writeln;
}

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.


import std.stdio, std.typecons, std.math, std.algorithm,
       std.random, std.traits, std.range, std.complex;

auto bruteForceClosestPair(T)(in T[] points) pure nothrow @nogc {
//  return pairwise(points.length.iota, points.length.iota)
//         .reduce!(min!((i, j) => abs(points[i] - points[j])));
  auto minD = Unqual!(typeof(T.re)).infinity;
  T minI, minJ;
  foreach (immutable i, const p1; points.dropBackOne)
    foreach (const p2; points[i + 1 .. $]) {
      immutable dist = abs(p1 - p2);
      if (dist < minD) {
        minD = dist;
        minI = p1;
        minJ = p2;
      }
    }
  return tuple(minD, minI, minJ);
}

auto closestPair(T)(T[] points) pure nothrow {
  static Tuple!(typeof(T.re), T, T) inner(in T[] xP, /*in*/ T[] yP)
  pure nothrow {
    if (xP.length <= 3)
      return xP.bruteForceClosestPair;
    const Pl = xP[0 .. $ / 2];
    const Pr = xP[$ / 2 .. $];
    immutable xDiv = Pl.back.re;
    auto Yr = yP.partition!(p => p.re <= xDiv);
    immutable dl_pairl = inner(Pl, yP[0 .. yP.length - Yr.length]);
    immutable dr_pairr = inner(Pr, Yr);
    immutable dm_pairm = dl_pairl[0]<dr_pairr[0] ? dl_pairl : dr_pairr;
    immutable dm = dm_pairm[0];
    const nextY = yP.filter!(p => abs(p.re - xDiv) < dm).array;

    if (nextY.length > 1) {
      auto minD = typeof(T.re).infinity;
      size_t minI, minJ;
      foreach (immutable i; 0 .. nextY.length - 1)
        foreach (immutable j; i + 1 .. min(i + 8, nextY.length)) {
          immutable double dist = abs(nextY[i] - nextY[j]);
          if (dist < minD) {
            minD = dist;
            minI = i;
            minJ = j;
          }
        }
      return dm <= minD ? dm_pairm :
                        typeof(return)(minD, nextY[minI], nextY[minJ]);
    } else
      return dm_pairm;
  }

  points.sort!q{ a.re < b.re };
  const xP = points.dup;
  points.sort!q{ a.im < b.im };
  return inner(xP, points);
}

void main() {
  alias C = complex;
  auto pts = [C(5,9), C(9,3), C(2), C(8,4), C(7,4), C(9,10), C(1,9),
              C(8,2), C(0,10), C(9,6)];
  pts.writeln;
  writeln("bruteForceClosestPair: ", pts.bruteForceClosestPair);
  writeln("          closestPair: ", pts.closestPair);

  rndGen.seed = 1;
  Complex!double[10_000] points;
  foreach (ref p; points)
    p = C(uniform(0.0, 1000.0) + uniform(0.0, 1000.0));
  writeln("bruteForceClosestPair: ", points.bruteForceClosestPair);
  writeln("          closestPair: ", points.closestPair);
}

The code provides two solutions to the Closest Pair of Points problem in a two-dimensional plane. The first function uses a brute force algorithm with a time complexity of O(n^2) to find the two points with the minimum distance between them. The second function uses a more efficient divide and conquer approach with a time complexity of O(n log n) to find the closest pair of points. The divide and conquer function sorts the points based on x and y coordinates, divides them into two halves, and recursively finds the closest pairs in each half. It then compares the closest pairs from both halves and the points lying in the strip around the dividing line to find the overall closest pair. The code also includes performance metrics for data generation and execution of both algorithms.


int[3] array;
array[0] = 5;
// array.length = 4; // compile-time error

int[] array;
array ~= 5; // append 5
array.length = 3;
array[3] = 17; // runtime error: out of bounds. check removed in release mode.
array = [2, 17, 3];
writefln(array.sort); // 2, 3, 17

int[int] array;
// array ~= 5; // it doesn't work that way!
array[5] = 17;
array[6] = 20;
// prints "[5, 6]" -> "[17, 20]" - although the order is not specified.
writefln(array.keys, " -> ", array.values);
assert(5 in array); // returns a pointer, by the way
if (auto ptr = 6 in array) writefln(*ptr); // 20

The code creates a collection in a statically-typed language, adds values to it, and reviews examples related to various types of collections such as arrays, associative arrays, linked lists, queues, sets, and stacks. It also includes the use of static, dynamic, and associative arrays in D programming language.


void main() @safe /*@nogc*/ {
    import std.stdio, std.algorithm, std.typecons, std.conv;

    static struct Bounty {
        int value;
        double weight, volume;
    }

    immutable Bounty panacea = {3000,  0.3, 0.025};
    immutable Bounty ichor =   {1800,  0.2, 0.015};
    immutable Bounty gold =    {2500,  2.0, 0.002};
    immutable Bounty sack =    {   0, 25.0, 0.25 };

    immutable maxPanacea = min(sack.weight / panacea.weight,
                               sack.volume / panacea.volume).to!int;
    immutable maxIchor   = min(sack.weight / ichor.weight,
                               sack.volume / ichor.volume).to!int;
    immutable maxGold    = min(sack.weight / gold.weight,
                               sack.volume / gold.volume).to!int;

    Bounty best = {0, 0, 0};
    Tuple!(int, int, int) bestAmounts;

    foreach (immutable nPanacea; 0 .. maxPanacea)
        foreach (immutable nIchor; 0 .. maxIchor)
            foreach (immutable nGold; 0 .. maxGold) {
                immutable Bounty current = {
                    value: nPanacea * panacea.value +
                           nIchor * ichor.value +
                           nGold * gold.value,
                    weight: nPanacea * panacea.weight +
                            nIchor * ichor.weight +
                            nGold * gold.weight,
                    volume: nPanacea * panacea.volume +
                            nIchor * ichor.volume +
                            nGold * gold.volume};

                if (current.value > best.value &&
                    current.weight <= sack.weight &&
                    current.volume <= sack.volume) {
                    best = Bounty(current.value, current.weight, current.volume);
                    bestAmounts = tuple(nPanacea, nIchor, nGold);
                }
            }

    writeln("Maximum value achievable is ", best.value);
    writefln("This is achieved by carrying (one solution) %d" ~
             " panacea, %d ichor and %d gold", bestAmounts[]);
    writefln("The weight to carry is %4.1f and the volume used is %5.3f",
             best.weight, best.volume);
}

"Calculate the maximum value of items a traveler can carry in his knapsack from Shangri La, considering the weight and volume constraints of the knapsack and the value, weight, and volume of each item. The code provides one of the four possible solutions to maximize the value taken."


import std.stdio;

void main() {
    for (int i = 1; ; i++) {
        write(i);
        if (i >= 10)
            break;
        write(", ");
    }

    writeln();
}

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.


import std.stdio, std.string, std.algorithm, std.range;

final class ArgumentException : Exception {
    this(string text) pure nothrow @safe /*@nogc*/ {
        super(text);
    }
}

alias TDependencies = string[][string];

string[][] topoSort(TDependencies d) pure /*nothrow @safe*/ {
    foreach (immutable k, v; d)
        d[k] = v.sort().uniq.filter!(s => s != k).array;
    foreach (immutable s; d.byValue.join.sort().uniq)
        if (s !in d)
            d[s] = [];

    string[][] sorted;
    while (true) {
        string[] ordered;

        foreach (immutable item, const dep; d)
            if (dep.empty)
                ordered ~= item;
        if (!ordered.empty)
            sorted ~= ordered.sort().release;
        else
            break;

        TDependencies dd;
        foreach (immutable item, const dep; d)
            if (!ordered.canFind(item))
                dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
        d = dd;
    }

    //if (!d.empty)
    if (d.length > 0)
        throw new ArgumentException(format(
            "A cyclic dependency exists amongst:\n%s", d));

    return sorted;
}

void main() {
    immutable data =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01           ieee dw01 dware gtech
dw02           ieee dw02 dware
dw03           std synopsys dware dw03 dw02 dw01 ieee gtech
dw04           dw04 ieee dw01 dware gtech
dw05           dw05 ieee dware
dw06           dw06 ieee dware
dw07           ieee dware
dware          ieee dware
gtech          ieee gtech
ramlib         std ieee
std_cell_lib   ieee std_cell_lib
synopsys";

    TDependencies deps;
    foreach (immutable line; data.splitLines)
        deps[line.split[0]] = line.split[1 .. $];

    auto depw = deps.dup;
    foreach (immutable idx, const subOrder; depw.topoSort)
        writefln("#%d : %s", idx + 1,  subOrder);

    writeln;
    depw = deps.dup;
    depw["dw01"] ~= "dw04";
    foreach (const subOrder; depw.topoSort) // Should throw.
        subOrder.writeln;
}

The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.


void main() {
    import std.stdio;
    import std.algorithm: startsWith, endsWith, find, countUntil;

    "abcd".startsWith("ab").writeln;      // true
    "abcd".endsWith("zn").writeln;        // false
    "abab".find("bb").writeln;            // empty array (no match)
    "abcd".find("bc").writeln;            // "bcd" (substring start
                                           //        at match)
    "abab".countUntil("bb").writeln;      // -1 (no match)
    "abab".countUntil("ba").writeln;      //  1 (index of 1st match)

    // std.algorithm.startsWith also works on arrays and ranges:
    [1, 2, 3].countUntil(3).writeln;      //  2
    [1, 2, 3].countUntil([2, 3]).writeln; //  1
}

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.


import std.stdio;

void main() {
    fourSquare(1,7,true,true);
    fourSquare(3,9,true,true);
    fourSquare(0,9,false,false);
}

void fourSquare(int low, int high, bool unique, bool print) {
    int count;

    if (print) {
        writeln("a b c d e f g");
    }
    for (int a=low; a<=high; ++a) {
        for (int b=low; b<=high; ++b) {
            if (!valid(unique, a, b)) continue;

            int fp = a+b;
            for (int c=low; c<=high; ++c) {
                if (!valid(unique, c, a, b)) continue;
                for (int d=low; d<=high; ++d) {
                    if (!valid(unique, d, a, b, c)) continue;
                    if (fp != b+c+d) continue;

                    for (int e=low; e<=high; ++e) {
                        if (!valid(unique, e, a, b, c, d)) continue;
                        for (int f=low; f<=high; ++f) {
                            if (!valid(unique, f, a, b, c, d, e)) continue;
                            if (fp != d+e+f) continue;

                            for (int g=low; g<=high; ++g) {
                                if (!valid(unique, g, a, b, c, d, e, f)) continue;
                                if (fp != f+g) continue;

                                ++count;
                                if (print) {
                                    writeln(a,' ',b,' ',c,' ',d,' ',e,' ',f,' ',g);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (unique) {
        writeln("There are ", count, " unique solutions in [",low,",",high,"]");
    } else {
        writeln("There are ", count, " non-unique solutions in [",low,",",high,"]");
    }
}

bool valid(bool unique, int needle, int[] haystack ...) {
    if (unique) {
        foreach (value; haystack) {
            if (needle == value) {
                return false;
            }
        }
    }
    return true;
}

The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.


IMPORT STD.STDIO, STD.DATETIME, STD.STRING, STD.CONV,
       STD.ALGORITHM, STD.ARRAY;

VOID PRINT_CALENDAR(IN UINT YEAR, IN UINT COLS)
IN {
    ASSERT(COLS > 0 && COLS <= 12);
} BODY {
    STATIC ENUM CAMEL_CASE = (STRING[] PARTS) PURE =>
        PARTS[0] ~ PARTS[1 .. $].MAP!CAPITALIZE.JOIN;

    IMMUTABLE ROWS = 12 / COLS + (12 % COLS != 0);
    MIXIN("AUTO DATE = " ~ "DATE(YEAR, 1, 1);".CAPITALIZE);
    ENUM STRING S1 = CAMEL_CASE("DAY OF WEEK".SPLIT);
    MIXIN(FORMAT("AUTO OFFS = CAST(INT)DATE.%S;", S1));
    CONST MONTHS = "JANUARY FEBRUARY MARCH APRIL MAY JUNE
        JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER"
        .SPLIT.MAP!CAPITALIZE.ARRAY;

    STRING[8][12] MONS;
    FOREACH (IMMUTABLE M; 0 .. 12) {
        MONS[M][0] = MONTHS[M].CENTER(21);
        MONS[M][1] = " " ~ "SU MO TU WE TH FR SA"
                           .SPLIT.MAP!CAPITALIZE.JOIN(" ");
        ENUM STRING S2 = CAMEL_CASE("DAYS IN MONTH".SPLIT);
        MIXIN(FORMAT("IMMUTABLE DIM = DATE.%S;", S2));
        FOREACH (IMMUTABLE D; 1 .. 43) {
            IMMUTABLE DAY = D > OFFS && D <= OFFS + DIM;
            IMMUTABLE STR = DAY ? FORMAT(" %2S", D-OFFS) : "   ";
            MONS[M][2 + (D - 1) / 7] ~= STR;
        }
        OFFS = (OFFS + DIM) % 7;
        DATE.ADD!"MONTHS"(1);
    }

    FORMAT("[%S %S]", "SNOOPY".CAPITALIZE, "PICTURE".CAPITALIZE)
    .CENTER(COLS * 24 + 4).WRITELN;
    WRITELN(YEAR.TEXT.CENTER(COLS * 24 + 4), "\N");
    FOREACH (IMMUTABLE R; 0 .. ROWS) {
        STRING[8] S;
        FOREACH (IMMUTABLE C; 0 .. COLS) {
            IF (R * COLS + C > 11)
                BREAK;
            FOREACH (IMMUTABLE I, LINE; MONS[R * COLS + C])
                S[I] ~= FORMAT("   %S", LINE);
        }
        WRITEFLN("%-(%S\N%)\N", S);
    }
}

STATIC THIS() {
    PRINT_CALENDAR(1969, 3);
}

import std.string;mixin(import("CALENDAR").toLower);void main(){}

The code provides an algorithm for a calendar task, formatted to fill a 132-character wide page, inspired by 1969 era line printers. The entire code is in uppercase, as it was often mandatory in the 1960s due to character encoding limitations. The code does not include Snoopy generation but outputs a placeholder instead. The code is stored in a text file named "CALENDAR", which is then imported and mixed-in by another source code file for safety.


void main() @safe {
    import std.stdio, std.range, std.algorithm, std.typecons, std.numeric;

    enum triples = (in uint n) pure nothrow @safe /*@nogc*/ =>
        iota(1, n + 1)
        .map!(z => iota(1, z + 1)
                   .map!(x => iota(x, z + 1).map!(y => tuple(x, y, z))))
        .joiner.joiner
        .filter!(t => t[0] ^^ 2 + t[1] ^^ 2 == t[2] ^^ 2 && t[].only.sum <= n)
        .map!(t => tuple(t[0 .. 2].gcd == 1, t[]));

    auto xs = triples(100);
    writeln("Up to 100 there are ", xs.count, " triples, ",
            xs.filter!q{ a[0] }.count, " are primitive.");
}

The code determines the number of Pythagorean triples, which are sets of three positive integers that satisfy the condition a^2 + b^2 = c^2 and a < b < c. It also identifies the number of these triples that are primitive, meaning the three numbers are co-prime. The code calculates these triples for perimeters up to 100. For extra credit, the code is optimized to handle larger perimeters up to 1,000,000, 10,000,000, and 100,000,000. The performance of the code is measured in terms of run-time.


Library: FLTK4d
 module Window;

 import fltk4d.all;

 void main() {
     auto window = new Window(300, 300, "A window");
     window.show;
     FLTK.run;
 }

Library: Derelict
Library: SDL
 import derelict.sdl.sdl;

 int main(char[][] args)
 {
     DerelictSDL.load();

     SDL_Event event;
     auto done = false;

     SDL_Init(SDL_INIT_VIDEO);
     scope(exit) SDL_Quit();

     SDL_SetVideoMode(1024, 768, 0, SDL_OPENGL);
     SDL_WM_SetCaption("My first Window", "SDL test");

     while (!done)
     {
         if (SDL_PollEvent(&event) == 1)
         {
             switch (event.type)
 	     {
                 case SDL_QUIT:
 	              done = true;
 		          break;
 		 default:
 		      break;
 	     }
 	 }
     }

    return 0;
 }

Library: QD

 import qd;

 void main() {
   screen(640, 480);
   while (true) events();
 }

Create a GUI window using QD, a wrapper around SDL, which can handle close requests.


void main() {
    import std.stdio, std.ascii, std.algorithm, std.range;

    uint[26] frequency;

    foreach (const buffer; "unixdict.txt".File.byChunk(2 ^^ 15))
        foreach (immutable c; buffer.filter!isAlpha)
            frequency[c.toLower - 'a']++;

    writefln("%(%(%s, %),\n%)", frequency[].chunks(10));
}

Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.


struct SLinkedNode(T) {
    T data;
    typeof(this)* next;
}

void main() {
    alias SLinkedNode!int N;
    N* n = new N(10);
}

define a data structure for a singly-linked list element. This element holds a numeric value and a mutable link to the next element. The code also includes references to various related data structures and operations, such as arrays, collections, doubly-linked lists, queues, sets, stacks, and generic template-based node elements. Additionally, it mentions the Phobos library's singly-linked list and Tango's LinkSeq collection.


import std.stdio, std.math;

enum width = 1000, height = 1000; // Image dimension.
enum length = 400;                // Trunk size.
enum scale = 6.0 / 10;            // Branch scale relative to trunk.

void tree(in double x, in double y, in double length, in double angle) {
    if (length < 1)
        return;
    immutable x2 = x + length * angle.cos;
    immutable y2 = y + length * angle.sin;
    writefln("<line x1='%f' y1='%f' x2='%f' y2='%f' " ~
             "style='stroke:black;stroke-width:1'/>", x, y, x2, y2);
    tree(x2, y2, length * scale, angle + PI / 5);
    tree(x2, y2, length * scale, angle - PI / 5);
}

void main() {
    "<svg width='100%' height='100%' version='1.1'
     xmlns='http://www.w3.org/2000/svg'>".writeln;
    tree(width / 2.0, height, length, 3 * PI / 2);
    "</svg>".writeln;
}

import grayscale_image, turtle;

void tree(Color)(Image!Color img, ref Turtle t, in uint depth,
                 in real step, in real scale, in real angle) {
    if (depth == 0) return;
    t.forward(img, step);
    t.right(angle);
    img.tree(t, depth - 1, step * scale, scale, angle);
    t.left(2 * angle);
    img.tree(t, depth - 1, step * scale, scale, angle);
    t.right(angle);
    t.forward(img, -step);
}

void main() {
    auto img = new Image!Gray(330, 300);
    auto t = Turtle(165, 270, -90);
    img.tree(t, 10, 80, 0.7, 30);
    img.savePGM("fractal_tree.pgm");
}

import dfl.all;
import std.math;

class FractalTree: Form {

    private immutable DEG_TO_RAD = PI / 180.0;

    this() {
        width = 600;
        height = 500;
        text = "Fractal Tree";
        backColor = Color(0xFF, 0xFF, 0xFF);
        startPosition = FormStartPosition.CENTER_SCREEN;
        formBorderStyle = FormBorderStyle.FIXED_DIALOG;
        maximizeBox = false;
    }

    private void drawTree(Graphics g, Pen p, int x1, int y1, double angle, int depth) {
        if (depth == 0) return;
        int x2 = x1 + cast(int) (cos(angle * DEG_TO_RAD) * depth * 10.0);
        int y2 = y1 + cast(int) (sin(angle * DEG_TO_RAD) * depth * 10.0);
        g.drawLine(p, x1, y1, x2, y2);
        drawTree(g, p, x2, y2, angle - 20, depth - 1);
        drawTree(g, p, x2, y2, angle + 20, depth - 1);
    }

    protected override void onPaint(PaintEventArgs ea){
        super.onPaint(ea);
        Pen p = new Pen(Color(0, 0xAA, 0));
        drawTree(ea.graphics, p, 300, 450, -90, 9);
    }
}

int main() {
    int result = 0;
    try {
        Application.run(new FractalTree);
    } catch(Exception e) {
        msgBox(e.msg, "Fatal Error", MsgBoxButtons.OK, MsgBoxIcon.ERROR);
        result = 1;
    }
    return result;
}

The code utilizes the turtle and grayscale image modules to generate and draw a fractal tree. It begins by drawing the trunk, then splits the end of the trunk at a certain angle to create two branches. This process is repeated until a desired level of branching is achieved. The code is written in DFL.


import std.stdio, std.math, std.algorithm;

T[] factors(T)(in T n) pure nothrow {
    if (n == 1)
        return [n];

    T[] res = [1, n];
    T limit = cast(T)real(n).sqrt + 1;
    for (T i = 2; i < limit; i++) {
        if (n % i == 0) {
            res ~= i;
            immutable q = n / i;
            if (q > i)
                res ~= q;
        }
    }

    return res.sort().release;
}

void main() {
    writefln("%(%s\n%)", [45, 53, 64, 1111111].map!factors);
}

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.