Algorithms in Different Languages

Featured

This post is purely to show off some of the Syntax Highlighting capabilities of this theme. All code snippets are from Rosetta Code.

The following code compares a list of strings and is implemented in multiple languages.

AppleScript

-- allEqual :: [String] -> Bool
on allEqual(xs)
    _and(zipWith(my _equal, xs, rest of xs))
end allEqual
 
-- azSorted :: [String] -> Bool
on azSorted(xs)
    _and(zipWith(my azBeforeOrSame, xs, rest of xs))
end azSorted
 
-- _equal :: a -> a -> Bool
on _equal(a, b)
    a = b
end _equal
 
-- azBefore :: String -> String -> Bool
on azBeforeOrSame(a, b)
    a ≥ b
end azBeforeOrSame
 
-- _and :: [a] -> Bool
on _and(xs)
    foldr(_equal, true, xs)
end _and
 
 
-- TEST
on run
    set lstA to ["isiZulu", "isiXhosa", "isiNdebele", "Xitsonga", "Tshivenda", ¬
        "Setswana", "Sesotho sa Leboa", "Sesotho", "English", "Afrikaans"]
 
    set lstB to ["Afrikaans", "English", "Sesotho", "Sesotho sa Leboa", "Setswana", ¬
        "Tshivenda", "Xitsonga", "isiNdebele", "isiXhosa", "isiZulu"]
 
    set lstC to ["alpha", "alpha", "alpha", "alpha", "alpha", "alpha", "alpha", ¬
        "alpha", "alpha", "alpha"]
 
 
    {allEqual:map(allEqual, [lstA, lstB, lstC]), azSorted:map(azSorted, [lstA, lstB, lstC])}
 
    -- > {allEqual:{false, false, true}, azSorted:{false, true, true}}
end run
 
 
 
-- GENERIC FUNCTIONS
 
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from lng to 1 by -1
            set v to lambda(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldr
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to lambda(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
    set nx to length of xs
    set ny to length of ys
    if nx < 1 or ny < 1 then
        {}
    else
        set lng to cond(nx < ny, nx, ny)
        set lst to {}
        tell mReturn(f)
            repeat with i from 1 to lng
                set end of lst to lambda(item i of xs, item i of ys)
            end repeat
            return lst
        end tell
    end if
end zipWith
 
-- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b)
on cond(bool, f, g)
    if bool then
        f
    else
        g
    end if
end cond
 
-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property lambda : f
        end script
    end if
end mReturn

C

#include <stdio.h>
#include <string.h>
 
int strings_are_equal(char * * strings, int nstrings)
{
  int result = 1;
 
  while (result && (--nstrings > 0))
  {
    result = !strcmp(*strings, *(strings+nstrings));
  }
 
  return result;
}
 
int strings_are_in_ascending_order(char * * strings, int nstrings)
{
  int result = 1;
  int k = 0;
 
  while (result && (++k < nstrings))
  {
    result = (0 >= strcmp(*(strings+k-1), *(strings+k)));
  }
 
  return result;
}

C#

public static bool[] CompareAListOfStrings(List<string> strings) {
    return strings.Count < 2 ? new [] { true, true }
        : new [] {
            strings.Distinct().Count() < 2,
            Enumerable.Range(1, strings.Count - 1).All(i => string.Compare(strings[i-1], strings[i]) < 0)
    };
}

 

C++

#include <algorithm>
#include <string>
 
std::all_of( ++(strings.begin()), strings.end(),
             [&](std::string a){ return a == strings.front(); } )  // All equal
 
std::is_sorted( strings.begin(), strings.end(),
                [](std::string a, std::string b){ return !(b < a); }) )  // Strictly ascending

F#

let (!) f s = Seq.isEmpty s || Seq.forall2 f s (Seq.tail s)

let allEqual = !(=)
let ascending = !(<)

Fortran

      INTEGER MANY,LONG
      PARAMETER (LONG = 6,MANY = 4)	!Adjust to suit.
      CHARACTER*(LONG) STRINGS(MANY)	!A list of text strings.
      STRINGS(1) = "Fee"
      STRINGS(2) = "Fie"
      STRINGS(3) = "Foe"
      STRINGS(4) = "Fum"
      IF (ALL(STRINGS(1:MANY - 1) .LT. STRINGS(2:MANY))) THEN
        WRITE (6,*) MANY," strings: strictly increasing in order."
       ELSE
        WRITE (6,*) MANY," strings: not strictly increasing in order."
      END IF
      IF (ALL(STRINGS(1:MANY - 1) .EQ. STRINGS(2:MANY))) THEN
        WRITE (6,*) MANY," strings: all equal."
       ELSE
        WRITE (6,*) MANY," strings: not all equal."
      END IF
      END

Go

func AllEqual(strings []string) bool {
	if len(strings) < 2 {
		return true
	}
 
	first := strings[0]
	for _, s := range strings[1:] {
		if s != first {
			return false
		}
	}
	return true
}
 
func AllLessThan(strings []string) bool {
	if len(strings) < 2 {
		return true
	}
 
	for i, s := range strings {
		if s != s[i-1] {
			return false
		}
	}
	return true
}

Java

import java.util.Arrays;
 
public class CompareListOfStrings {
 
    public static void main(String[] args) {
        String[][] arr = {{"AA", "AA", "AA", "AA"}, {"AA", "ACB", "BB", "CC"}};
        for (String[] a : arr) {
            System.out.printf("%s%n%s%n%s%n", Arrays.toString(a),
            Arrays.stream(a).distinct().count() < a.length,
            Arrays.equals(Arrays.stream(a).distinct().sorted().toArray(), a));
        }
    }
}

JavaScript

function allEqual(a) {
  var out = true, i = 0;
  while (++i<a.length) {
    out = out && (a[i-1] === a[i]);
  } return out;
}
 
function azSorted(a) {
  var out = true, i = 0;
  while (++i<a.length) {
    out = out && (a[i-1] < a[i]);
  } return out;
}
 
var e = ['AA', 'AA', 'AA', 'AA'], s = ['AA', 'ACB', 'BB', 'CC'], empty = [], single = ['AA'];
console.log(allEqual(e)); // true
console.log(allEqual(s)); // false
console.log(allEqual(empty)); // true
console.log(allEqual(single)); // true
console.log(azSorted(e)); // false
console.log(azSorted(s)); // true
console.log(azSorted(empty)); // true
console.log(azSorted(single)); // true

Perl

use List::Util 1.33 qw(all);
 
all { $strings[0] eq $strings[$_] } 1..$#strings  # All equal
all { $strings[$_-1] lt $strings[$_] } 1..$#strings  # Strictly ascending

PowerShell

function IsAscending ( [string[]]$Array ) { ( 0..( $Array.Count - 2 ) ).Where{ $Array[$_] -le $Array[$_+1] }.Count -eq $Array.Count - 1 }
function IsEqual     ( [string[]]$Array ) { ( 0..( $Array.Count - 2 ) ).Where{ $Array[$_] -eq $Array[$_+1] }.Count -eq $Array.Count - 1 }
 
IsAscending 'A', 'B', 'B', 'C'
IsAscending 'A', 'C', 'B', 'C'
IsAscending 'A', 'A', 'A', 'A'
 
IsEqual     'A', 'B', 'B', 'C'
IsEqual     'A', 'C', 'B', 'C'
IsEqual     'A', 'A', 'A', 'A'

Python

all(a == nexta for a, nexta in zip(strings, strings[1:]) # All equal
all(a < nexta for a, nexta in zip(strings, strings[1:]) # Strictly ascending

 

Leave a Reply

Your email address will not be published. Required fields are marked *