sub encode {
    my $source = shift;
    my $key = shift;
    my $out = q();

    @ka = split //, $key;
    foreach $ch (split //, $source) {
        $idx = ord($ch) - 32;
        $out .= $ka[$idx];
    }

    return $out;
}

sub decode {
    my $source = shift;
    my $key = shift;
    my $out = q();

    foreach $ch (split //, $source) {
        $idx = index $key, $ch;
        $val = chr($idx + 32);
        $out .= $val;
    }

    return $out;
}

my $key = q(]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\C1yxJ);
my $text = "Here we have to do is there will be a input/source "
         . "file in which we are going to Encrypt the file by replacing every "
         . "upper/lower case alphabets of the source file with another "
         . "predetermined upper/lower case alphabets or symbols and save "
         . "it into another output/encrypted file and then again convert "
         . "that output/encrypted file into original/decrypted file. This "
         . "type of Encryption/Decryption scheme is often called a "
         . "Substitution Cipher.";

my $ct = encode($text, $key);
print "Encoded: $ct\n";

my $pt = decode($ct, $key);
print "Decoded: $pt\n";


constant plain = tagset('Z','A')&tagset('z','a'),
         key = shuffle(plain)

function encode(string s, integer decrypt=false)
    sequence {p,k} = iff(decrypt?{plain,key}:{key,plain})
    for i=1 to length(s) do
        integer ki = find(s[i],p)
        if ki then s[i] = k[ki] end if
    end for
    return s
end function

string original = "A simple example.",
       encoded = encode(original),
       decoded = encode(encoded, true)

printf(1,"original: %s\nencoded: %s\ndecoded: %s\n",{original,encoded,decoded})


include ..\Utilitys.pmt

" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
" VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
"A simple example"

def Encode
    >ps
    tps not if >ps swap ps> endif
    len for
        >ps
        tps get swap >ps
        rot swap find
        rot swap get
        ps> swap ps> set
    endfor
    ps> not if >ps swap ps> endif
enddef

dup ?
true Encode dup ?
false Encode ?


<?php

$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key      = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq';

// Encode input.txt, and save result in output.txt
file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key));

$source  = file_get_contents('input.txt');
$encoded = file_get_contents('output.txt');
$decoded = strtr($encoded, $key, $alphabet);

echo
    '== SOURCE ==', PHP_EOL,
    $source, PHP_EOL, PHP_EOL,
    '== ENCODED ==', PHP_EOL,
    $encoded, PHP_EOL, PHP_EOL,
    '== DECODED ==', PHP_EOL,
    $decoded, PHP_EOL, PHP_EOL;


main =>
  S = "The quick brown fox jumped over the lazy dog",
  cypher(S,E),  % encrypt
  println(E),

  cypher(D, E), % decrypt
  println(D),

  S == D,
  println(ok).

cypher(O, S) :-
  nonvar(O),
  var(S),
  sub_chars(O,S).
cypher(O, S) :-
  nonvar(S),
  var(O),
  sub_chars(O,S).

base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ").
subs("VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWob LkESYMTN").

sub_chars(Original,Subbed) :-
  base(Base),
  subs(Subs),
  maplist($sub_char(Base,Subs),Original,Subbed).

sub_char([Co|_],[Cs|_],Co,Cs) :- !.
sub_char([_|To],[_|Ts], Co, Cs) :- sub_char(To,Ts,Co,Cs).

maplist(Goal, List1, List2) :-
    maplist_(List1, List2, Goal).

maplist_([], X, _) :- X = [].
maplist_([Elem1|Tail1],
         [Elem2|Tail2],
         Goal) :-
    call(Goal, Elem1, Elem2),
    maplist_(Tail1, Tail2, Goal).


(setq *A (chop "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"))
(setq *K (chop "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"))

(de cipher (Str D)
   (let (K *K  A *A)
      (and D (xchg 'A 'K))
      (pack
         (mapcar
            '((N)
               (or
                  (pick
                     '((A K) (and (= A N) K))
                     A
                     K )
                  N ) )
            (chop Str) ) ) ) )
(and
   (println 'encode (cipher "The quick brown fox jumped over the lazy dog's back"))
   (println 'decode (cipher @ T)) )


string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string key      = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN";
mapping key_mapping = mkmapping(alphabet/1, key/1);
object c = Crypto.Substitution()->set_key(key_mapping);

string msg = "The quick brown fox jumped over the lazy dogs";
string msg_enc = c->encrypt(msg);
string msg_dec = c->decrypt(msg_enc);

write("Encrypted: %s\n", msg_enc);
write("Decrypted: %s\n", msg_dec);


cypher(O, S) :-
	nonvar(O),
	var(S),
	atom_chars(O,Oc),
	sub_chars(Oc,Sc),
	atom_chars(S,Sc).
cypher(O, S) :-
	nonvar(S),
	var(O),
	atom_chars(S,Sc),
	sub_chars(Oc,Sc),
	atom_chars(O,Oc).

% mapping based on ADA implementation but have added space character
base(['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,' ']).
subs(['V',s,c,i,'B',j,e,d,g,r,z,y,'H',a,l,v,'X','Z','K',t,'U','P',u,m,'G',f,'I',w,'J',x,q,'O','C','F','R','A',p,n,'D',h,'Q','W',o,b,' ','L',k,'E','S','Y','M','T','N']).

sub_chars(Original,Subbed) :-
	base(Base),
	subs(Subs),
	maplist(sub_char(Base,Subs),Original,Subbed).

sub_char([Co|_],[Cs|_],Co,Cs) :- !.
sub_char([_|To],[_|Ts], Co, Cs) :- sub_char(To,Ts,Co,Cs).


from string import printable
import random

EXAMPLE_KEY = ''.join(sorted(printable, key=lambda _:random.random()))

def encode(plaintext, key):
    return ''.join(key[printable.index(char)] for char in plaintext)

def decode(plaintext, key):
    return ''.join(printable[key.index(char)] for char in plaintext)

original = "A simple example."
encoded = encode(original, EXAMPLE_KEY)
decoded = decode(encoded, EXAMPLE_KEY)
print("""The original is: {}
Encoding it with the key: {}
Gives: {}
Decoding it by the same key gives: {}""".format(
    original, EXAMPLE_KEY, encoded, decoded))


  [ stack ]                      is encryption  (   --> s )
  [ stack ]                      is decryption  (   --> s )

  [ [] 95 times [ i^ join ]
    shuffle encryption put ]     is makeencrypt (   -->   )

  [ encryption share
    0 95 of swap
    witheach
      [ i^ unrot poke ]
    decryption put ]             is makedecrypt (   -->   )

  [ makeencrypt makedecrypt ]    is makekeys    (   -->   )

  [ witheach [ char ! + emit ] ] is echokey     ( s -->   )

  [ encryption release
    decryption release ]         is releasekeys (   -->   )

  [ [] swap witheach
      [ dup char ! char ~ 1+
        within if
          [ char ! -
            encryption share
            swap peek char ! + ]
        join ] ]                 is encrypt     ( $ --> $ )

  [ [] swap witheach
      [ dup char ! char ~ 1+
        within if
          [ char ! -
            decryption share
            swap peek char ! + ]
        join ] ]                 is decrypt    ( $ --> $ )

  randomise
  makekeys
  say "Encryption key is: " encryption share echokey cr
  say "Decryption key is: " decryption share echokey cr
  cr
  $ "Encryption matters, and it is not just for spies and philanderers."
  say "Plaintext: " dup echo$ cr
  say "Encrypted: " encrypt dup echo$ cr
  say "Decrypted: " decrypt echo$ cr
  releasekeys


#lang racket/base
(require racket/list racket/function racket/file)

(define abc "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")

;; Used to generate my-key for examples
(define (random-key (alphabet abc))
  (list->string (shuffle (string->list alphabet))))

(define (cypher/decypher key (alphabet abc))
  ;; alist is fine, hashes are better over 40 chars... so alist for
  ;; abc, hash for ASCII.
  (define ab-chars (string->list alphabet))
  (define ky-chars (string->list key))
  (define cypher-alist (map cons ab-chars ky-chars))
  (define decypher-alist (map cons ky-chars ab-chars))
  (define ((subst-map alist) str)
    (list->string (map (lambda (c) (cond [(assoc c alist) => cdr] [else c]))
                       (string->list str))))
  (values (subst-map cypher-alist)
          (subst-map decypher-alist)))

(define (cypher/decypher-files key (alphabet abc))
  (define-values (cypher decypher) (cypher/decypher key alphabet))
  (define ((convert-file f) in out #:exists (exists-flag 'error))
     (curry with-output-to-file out #:exists exists-flag
            (lambda () (display (f (file->string in))))))
  (values (convert-file cypher)
          (convert-file decypher)))

(module+ test
  (require rackunit)
  (define my-key "LXRWzUrIYPJiVQyMwKudbAaDjSEefvhlqmOkGcBZCFsNpxHTgton")

  (define-values (cypher decypher) (cypher/decypher my-key abc))

  (define in-text #<<T
The quick brown fox...
.. jumped over
the lazy dog!
T
    )
  (define cypher-text (cypher in-text))

  (define plain-text (decypher cypher-text))
  (displayln cypher-text)
  (check-equal? plain-text in-text)

  (define-values (file-cypher file-decypher) (cypher/decypher-files my-key abc))
  (file-cypher "data/substitution.in.txt" "data/substitution.crypt.txt" #:exists 'replace)
  (file-decypher "data/substitution.crypt.txt" "data/substitution.plain.txt" #:exists 'replace)
  (displayln "---")
  (displayln (file->string "data/substitution.crypt.txt"))
  (check-equal? (file->string "data/substitution.in.txt")
                (file->string "data/substitution.plain.txt")))


my $chr = (' ' .. '}').join('');
my $key = $chr.comb.pick(*).join('');

# Be very boring and use the same key every time to fit task reqs.
$key = q☃3#}^",dLs*>tPMcZR!fmC rEKhlw1v4AOgj7Q]YI+|pDB82a&XFV9yzuH<WT%N;iS.0e:`G\n['[email protected]_{bk)=-5qx(/?$JoU☃;

sub MAIN ($action = 'encode', $file = '') {

    die 'Only options are encode or decode.' unless $action ~~ any 'encode'|'decode';

    my $text = qq:to/END/;
        Here we have to do is there will be a input/source file in which
        we are going to Encrypt the file by replacing every upper/lower
        case alphabets of the source file with another predetermined
        upper/lower case alphabets or symbols and save it into another
        output/encrypted file and then again convert that output/encrypted
        file into original/decrypted file. This type of Encryption/Decryption
        scheme is often called a Substitution Cipher.
        END

    $text = $file.IO.slurp if $file;

    say "Key = $key\n";

    if $file {
        say &::($action)($text);
    } else {
        my $encoded;
        say "Encoded text: \n {$encoded = encode $text}";
        say "Decoded text: \n {decode $encoded}";
    }
}

sub encode ($text) { $text.trans($chr => $key) }

sub decode ($text) { $text.trans($key => $chr) }


/*REXX program implements & demonstrates a substitution cipher for the records in a file*/
parse arg fid.1 fid.2 fid.3 fid.4 .              /*obtain optional arguments from the CL*/
if fid.1==''  then fid.1= "CIPHER.IN"            /*Not specified?  Then use the default.*/
if fid.2==''  then fid.2= "CIPHER.OUT"           /* "      "         "   "   "     "    */
if fid.3==''  then fid.3= "CIPHER.KEY"           /* "      "         "   "   "     "    */
if fid.4==''  then fid.4= "CIPHER.ORI"           /* "      "         "   "   "     "    */
say '    input file: '   fid.1                   /*display the fileID used for  input.  */
say '   output file: '   fid.2                   /*   "     "     "     "   "  output.  */
say '   cipher file: '   fid.3                   /*   "     "     "     "   " cipher-key*/
say 'decrypted file: '   fid.4                   /*   "     "     "     "   "  decrypted*/
call closer                                      /*close all files in case they're open.*/
           do c=1  while lines(fid.3)\==0        /*read (hopefully 2 records) from key. */
           @.c= space( linein(fid.3), 0)         /*assign input record to an  @.  array.*/
           end   /*c*/
c= c - 1                                         /*adjust the number of records (for DO)*/
if c==0                       then call ser fid.3,  'not found or is empty.'
if c>2                        then call ser fid.3,  'has too many records  (>2).'
if c<2                        then call ser fid.3,  'has too few records   (<2).'
if length(@.1)\==length(@.2)  then call ser fid.3,  'has unequal length records.'
call encrypt  fid.1, fid.2                       /*encrypt the input file  ───►  output.*/
[email protected].1;    @.[email protected].2;   @.2=_                       /*switch the cipher keys for decryption*/
call encrypt  fid.2, fid.4                       /*decrypt the output file ───► decrypt.*/
call show     'cipher file ('fid.3")" , fid.3    /*display the cipher─key file.         */
call show      'input file ('fid.1")" , fid.1    /*   "     "     input     "           */
call show     'output file ('fid.2")" , fid.2    /*   "     "    output     "           */
call show ' decrypted file ('fid.4")" , fid.4    /*   "     "   decrypted   "           */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
closer:  do f=1  for 4;   call lineout fid.f;    end  /*f*/;            say;      return
ser:     say  '***error!***  file '     arg(1)" "    arg(2);                      exit
show:    say;   say center( arg(1), 79, '═');        "TYPE"  arg(2);              return
/*──────────────────────────────────────────────────────────────────────────────────────*/
encrypt: parse arg @in,@out                      /* [↓] effectively deletes @out file by*/
         call lineout @out,,1                    /*setting pointer to rec#1 for the file*/
                                do j=0  while lines(@in)\==0       /*read the input file*/
                                call lineout @out, translate( linein(@in), @.2, @.1)
                                end   /*j*/
         if j==0  then call ser @in, 'is empty.' /*was the file not found or was empty? */
         say @in  ' records processed: '   j     /*show the number of records processed.*/
         call closer                             /*close all the files to be neat & safe*/
         return


# Project : Substitution Cipher

plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ciphertext = "ZEBRASCDFGHIJKLMNOPQTUVWXY"
test = "flee at once. we are discovered!"
encrypt = "SIAA ZQ LKBA. VA ZOA RFPBLUAOAR!"

see "Plaintext : " + plaintext + nl
see "Ciphertext : " + ciphertext + nl
see "Test : " + test + nl
see "Encoded : "
encodetext = encode(test)
see encodetext + nl
see "Decoded : "
decodetext = decode(encodetext)
see decodetext + nl

func encode(test)
        str = ""
        for n = 1 to len(test)
              pos = substr(plaintext, upper(test[n]))
              if test[n] = " "
                 str = str + " "
              elseif test[n] = "!"
                 str = str + "!"
              elseif test[n] = "."
                 str = str + "."
              else
                 str = str + substr(ciphertext, pos, 1)
              ok
        next
        return str

func decode(test)
        str = ""
        for n = 1 to len(encodetext)
              pos = substr(ciphertext, upper(encodetext[n]))
              if test[n] = " "
                 str = str + " "
              elseif test[n] = "!"
                 str = str + "!"
              elseif test[n] = "."
                 str = str + "."
              else
                 str = str + lower(substr(plaintext, pos, 1))
              ok
        next
        return str


Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Key      = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"

def encrypt(str) = str.tr(Alphabet, Key)
def decrypt(str) = str.tr(Key, Alphabet)

str = 'All is lost, he thought. Everything is ruined. It’s ten past three.'
p encrypted =   encrypt(str)
p decrypt(encrypted)


object SubstitutionCipher extends App {
  private val key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N" + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
  private val text =
    """"It was still dark, in the early morning hours of the twenty-second of December
      | 1946, on the second floor of the house at Schilderskade 66 in our town,
      | when the hero of this story, Frits van Egters, awoke."""".stripMargin

  val enc = encode(text)
  println("Encoded: " + enc)
  println("Decoded: " + decode(enc))

  private def encode(s: String) = {
    val sb = new StringBuilder(s.length)
    s.map {
      case c if (' ' to '~').contains(c) => sb.append(key(c.toInt - 32))
      case _ =>
    }
    sb.toString
  }

  private def decode(s: String) = {
    val sb = new StringBuilder(s.length)
    s.map {
      case c if (' ' to '~').contains(c) =>
        sb.append((key.indexOf(c.toInt) + 32).toChar)
      case _ =>
    }
    sb.toString
  }
}


module SubstitutionCipher {

    const key = %c"]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"

    func encode(String s) {
        var r = ""
        s.each {|c|
            r += key[c.ord - 32]
        }
        return r
    }

    func decode(String s) {
        var r = ""
        s.each {|c|
            r += (key.first_index { _ == c } + 32 -> chr)
        }
        return r
    }
}

with ("The quick brown fox jumps over the lazy dog, who barks VERY loudly!") { |s|
    var enc = SubstitutionCipher::encode(s)
    var dec = SubstitutionCipher::decode(enc)
    say("Original: ", s, "\n -> Encoded: ", enc, "\n -> Decoded: ", dec)
}


oo::class create SubCipher {
    variable Alphabet
    variable Key
    variable EncMap
    variable DecMap
    constructor {{alphabet abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ} {cipherbet ""}} {
        set Alphabet $alphabet
        if {$cipherbet eq ""} {
            my key [my RandomKey]
        } else {
            my key $cipherbet
        }
    }
    method key args {
        if {$args eq ""} {
            return $Key
        } elseif {[llength $args] > 1} {
            throw {TCL WRONGARGS} "Expected \"[self class] key\" or \"[self class]\" key keystring"
        }
        lassign $args s

        set size [string length $Alphabet]
        if {[string length $s] != $size} {
            return -code error "Key must be $size chars long!"
        }
        set encmap {}
        set decmap {}
        foreach c [split $Alphabet {}] e [split $s {}] {
            dict set encmap $c $e
            dict set decmap $e $c
        }
        if {[dict size $encmap] != $size} {
            return -code error "Alphabet has repeating characters!"
        }
        if {[dict size $decmap] != $size} {
            return -code error "Key has repeating characters!"
        }
        set Key $s
        set EncMap $encmap
        set DecMap $decmap
    }
    method RandomKey {} {
        set chars $Alphabet
        set key {}
        for {set n [string length $chars]} {$n > 0} {incr n -1} {
            set i [expr {int(rand()*$n)}]
            append key [string index $chars $i]
            set chars [string range $chars 0 $i-1][string range $chars $i+1 end]
        }
        return $key
    }

    method enc {s} {
        string map $EncMap $s
    }
    method dec {s} {
        string map $DecMap $s
    }
}


option explicit
const maxk=94
dim key(94)

a="I'm working on modernizing Rosetta Code's infrastructure. Starting with communications."&_
" Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)"

sub gen     'swaps items not previusly affected by a swap
  dim i,m,t
  for i=0 to ubound(key)
    key(i)=i+32
  next
  for i=0 to ubound(key)-1
    if key(i)=i+32 then
      m=i+int(rnd*(maxk-i))
     if key(m)=m+32 then
       t=key(m):key(m)=key(i):key(i)=t
     end if
   end if
  next
end sub

function viewkey
dim i,b
b=""
for i=1 to ubound(key)
   b=b&chr(key(i))
next
viewkey=b
end function

function iif(a,b,c) if a then iif=b else iif =c end if: end function

function docode(a)
  dim b,i,ch,n
  n=maxk+32
  b=""
  for i=1 to len(a)
   ch=asc(mid(a,i,1))
   'wscript.echo ch
   b=b&chr(key(iif (ch>n or ch<32,0,ch-32)))
  next
  docode=b
end function

randomize timer
dim a,b,c
gen
wscript.echo "Key:   " & viewkey & vbcrlf
wscript.echo "Original: " & a & Vbcrlf
b=docode(a)
wscript.echo "Encoded: "&  b & Vbcrlf
c=docode(b)
wscript.echo "Decoded: " & c & Vbcrlf
wscript.quit(0)


var key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6\%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"

var encode = Fn.new { |s|
    var res = ""
    for (c in s) res = res + key[c.bytes[0] - 32]
    return res
}

var decode = Fn.new { |s|
    var res = ""
    for (c in s) res = res + String.fromByte(key.indexOf(c) + 32)
    return res
}

var s = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
var enc = encode.call(s)
System.print("Encoded:  %(enc)")
System.print("Decoded:  %(decode.call(enc))")


class SubstitutionCipher{
   // 92 characters: " !"#$%&" ... "xyz{|}", doesn't include "~"
   const KEY="]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
             "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";
   fcn encode(s){ s.apply(fcn(c){ try{ KEY[c.toAsc()-32] }catch{ c } }) }
   fcn decode(s){ s.apply(fcn(c){ try{ (KEY.index(c)+32).toChar() }catch{ c } }) }
}


F primes_upto(limit)
   V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
   L(n) 0 .< Int(limit ^ 0.5 + 1.5)
      I is_prime[n]
         L(i) (n * n .< limit + 1).step(n)
            is_prime[i] = 0B
   R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)

F successive_primes(primes, diffs)
   [[Int]] results
   V dl = diffs.len

   L(i) 0 .< primes.len - dl
      V group = [0] * (dl + 1)
      group[0] = primes[i]
      L(j) i .+ dl
         I primes[j + 1] - primes[j] != diffs[j - i]
            L.break
         group[j - i + 1] = primes[j + 1]
      L.was_no_break
         results [+]= group

   R results

V prime_list = primes_upto(1'000'000)

print(‘For primes less than 1,000,000:-’)
L(diffs) [[2], [1], [2, 2], [2, 4], [4, 2], [6, 4, 2]]
   print(‘  For differences of #. ->’.format(diffs))
   V sp = successive_primes(prime_list, diffs)
   print(‘    First group   = ’sp[0])
   print(‘    Last group    = ’sp.last)
   print(‘    Number found  = ’sp.len)
   print()


BEGIN # find some sequences of primes where the gaps between the elements #
      # follow specific patterns                                          #
    # reurns a list of primes up to n #
    PROC prime list = ( INT n )[]INT:
         BEGIN
            # sieve the primes to n #
            INT no = 0, yes = 1;
            [ 1 : n ]INT p;
            p[ 1 ] := no; p[ 2 ] := yes;
            FOR i FROM 3 BY 2 TO n DO p[ i ] := yes OD;
            FOR i FROM 4 BY 2 TO n DO p[ i ] := no  OD;
            FOR i FROM 3 BY 2 TO ENTIER sqrt( n ) DO
                IF p[ i ] = yes THEN FOR s FROM i * i BY i + i TO n DO p[ s ] := no OD FI
            OD;
            # replace the sieve with a list #
            INT p pos := 0;
            FOR i TO n DO IF p[ i ] = yes THEN p[ p pos +:= 1 ] := i FI OD;
            p[ 1 : p pos ]
         END # prime list # ;
    # prints the elements of list #
    PROC print list = ( STRING name, []INT list )VOID:
         BEGIN
            print( ( name, "[" ) );
            FOR i FROM LWB list TO UPB list DO print( ( " ", whole( list[ i ], 0 ) ) ) OD;
            print( ( " ]" ) )
         END # print list # ;
    # attempts to find patterns in the differences of primes and prints the results #
    PROC try differences = ( []INT primes, []INT pattern )VOID:
         BEGIN
            INT    pattern length = ( UPB pattern - LWB pattern ) + 1;
            [ 1 :  pattern length + 1 ]INT first; FOR i TO UPB first DO first[ i ] := 0 OD;
            [ 1 :  pattern length + 1 ]INT last;  FOR i TO UPB last  DO last[  i ] := 0 OD;
            INT    count := 0;
            FOR p FROM LWB primes + pattern length TO UPB primes DO
                BOOL matched := TRUE;
                INT e pos    := LWB pattern;
                FOR e FROM p - pattern length TO p - 1
                WHILE matched := primes[ e + 1 ] - primes[ e ] = pattern[ e pos ]
                DO
                    e pos +:= 1
                OD;
                IF matched THEN
                    # found a matching sequence #
                    count +:= 1;
                    last   := primes[ p - pattern length : p @ 1 ];
                    IF count = 1 THEN first := last FI
                FI
            OD;
            print( ( "  Found ", whole( count, 0 ), " prime sequence(s) that differ by: " ) );
            print list( "", pattern );
            print( ( newline ) );
            IF count > 0 THEN
                # found at least one sequence #
                print list( "    first: ", first );
                print list( "    last: ",  last  );
                print( ( newline ) )
            FI;
            print( ( newline ) )
         END # try differences # ;
    INT max number = 1 000 000;
    []INT    p list = prime list( max number );
    print( ( "For primes up to ", whole( max number, 0 ), "...", newline ) );
    try differences( p list, ( 2 )               );try differences( p list, ( 1 )               );
    try differences( p list, ( 2, 2 )            );try differences( p list, ( 2, 4 )            );
    try differences( p list, ( 4, 2 )            );try differences( p list, ( 6, 4, 2 )         );
    try differences( p list, ( 2, 4, 6, 8 )      );try differences( p list, ( 2, 4, 6, 8, 10 )  );
    try differences( p list, ( 32, 16, 8, 4, 2 ) )
END


LIM: 1000000

findDiffs: function [r][
    if r=[1] -> return [[2 3]]
    i: 3
    tupled: map 0..dec size r 'x -> fold slice r 0 x [a b][a+b]
    diffs: new []
    while [i < LIM][
        if prime? i [
            prset: map tupled 't -> i + t
            if every? prset 'elem -> prime? elem [
                'diffs ++ @[@[i] ++ prset]
            ]
        ]
        i: i + 2
    ]

    diffs: filter diffs 'dd [
        some? range (first dd)+1 (last dd)-1 'x -> and? [prime? x][not? contains? dd x]
    ]
    return diffs
]

loop [[2] [1] [2 2] [2 4] [4 2] [6 4 2]] 'rng [
    print ["Differences of" join.with:", " to [:string] rng]
    diffs: findDiffs rng
    print ["\tFirst: " join.with:" " to [:string] first diffs]
    print ["\tLast: " join.with:" " to [:string] last diffs]
    print ["\tCount: " size diffs]
]


# syntax: GAWK -f SUCCESSIVE_PRIME_DIFFERENCES.AWK
BEGIN {
    for (i=lo=0; i<=hi=1000000; i++) {
      if (is_prime(i)) {
        p_arr[++p] = i
      }
    }
    printf("there are %d primes between %d - %d\n",p,lo,hi)
    fmt = "%-11s %5s %-15s %s\n"
    printf(fmt,"differences","count","first group","last group")
    for (a=1; a<=split("2;1;2,2;2,4;4,2;6,4,2;2,4,6;100;112",diff_arr,";"); a++) {
      diff_leng = split(diff_arr[a],tmp_arr,",")
      first_set = last_set = ""
      count = 0
      for (b=1; b<=p; b++) {
        str = ""
        for (c=1; c<=diff_leng; c++) {
          if (p_arr[b+c-1] + tmp_arr[c] == p_arr[b+c]) {
            str = (str == "") ? (p_arr[b+c-1] "," p_arr[b+c]) : (str "," p_arr[b+c])
          }
        }
        if (gsub(/,/,"&",str) == diff_leng) {
          count++
          if (first_set == "") {
            first_set = str
          }
          last_set = str
        }
      }
      printf(fmt,diff_arr[a],count,first_set,last_set)
    }
    exit(0)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}


#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

#define PRIME_COUNT 100000
int64_t PRIMES[PRIME_COUNT];
size_t primeSize = 0;

bool isPrime(int n) {
    size_t i = 0;

    for (i = 0; i < primeSize; i++) {
        int64_t p = PRIMES[i];
        if (n == p) {
            return true;
        }
        if (n % p == 0) {
            return false;
        }
        if (p * p > n) {
            break;
        }
    }

    return true;
}

void initialize() {
    int i;

    PRIMES[primeSize++] = 2;
    PRIMES[primeSize++] = 3;
    PRIMES[primeSize++] = 5;
    PRIMES[primeSize++] = 7;
    PRIMES[primeSize++] = 11;
    PRIMES[primeSize++] = 13;
    PRIMES[primeSize++] = 17;
    PRIMES[primeSize++] = 19;

    for (i = 21; primeSize < PRIME_COUNT;) {
        if (isPrime(i)) {
            PRIMES[primeSize++] = i;
        }
        i += 2;

        if (primeSize < PRIME_COUNT && isPrime(i)) {
            PRIMES[primeSize++] = i;
        }
        i += 2;
    }
}

void diff1(size_t diff) {
    int64_t pm0, pm1;
    int64_t fg1 = 0, fg2 = 0, lg1 = 0, lg2 = 0;
    size_t pos, count = 0;

    if (diff == 0) {
        return;
    }

    pm0 = PRIMES[0];
    for (pos = 1; pos < PRIME_COUNT; pos++) {
        pm1 = pm0;
        pm0 = PRIMES[pos];
        if (pm0 > 1000000) {
            break;
        }
        if (pm0 - pm1 == diff) {
            count++;
            if (fg1 == 0) {
                fg1 = pm1;
                fg2 = pm0;
            }
            lg1 = pm1;
            lg2 = pm0;
        }
    }

    printf("%ld|%d|%lld %lld|%lld %lld|\n", diff, count, fg1, fg2, lg1, lg2);
}

void diff2(size_t d0, size_t d1) {
    int64_t pm0, pm1, pm2;
    int64_t fg1 = 0, fg2, fg3, lg1, lg2, lg3;
    size_t pos, count = 0;

    if (d0 == 0 || d1 == 0) {
        return;
    }

    pm1 = PRIMES[0];
    pm0 = PRIMES[1];
    for (pos = 2; pos < PRIME_COUNT; pos++) {
        pm2 = pm1;
        pm1 = pm0;
        pm0 = PRIMES[pos];
        if (pm0 > 1000000) {
            break;
        }
        if (pm1 - pm2 == d0 && pm0 - pm1 == d1) {
            count++;
            if (fg1 == 0) {
                fg1 = pm2;
                fg2 = pm1;
                fg3 = pm0;
            }
            lg1 = pm2;
            lg2 = pm1;
            lg3 = pm0;
        }
    }

    printf("%d %d|%d|%lld %lld %lld|%lld %lld %lld|\n", d0, d1, count, fg1, fg2, fg3, lg1, lg2, lg3);
}

void diff3(size_t d0, size_t d1, size_t d2) {
    int64_t pm0, pm1, pm2, pm3;
    int64_t fg1 = 0, fg2, fg3, fg4, lg1, lg2, lg3, lg4;
    size_t pos, count = 0;

    if (d0 == 0 || d1 == 0 || d2 == 0) {
        return;
    }

    pm2 = PRIMES[0];
    pm1 = PRIMES[1];
    pm0 = PRIMES[2];
    for (pos = 3; pos < PRIME_COUNT; pos++) {
        pm3 = pm2;
        pm2 = pm1;
        pm1 = pm0;
        pm0 = PRIMES[pos];
        if (pm0 > 1000000) {
            break;
        }
        if (pm2 - pm3 == d0 && pm1 - pm2 == d1 && pm0 - pm1 == d2) {
            count++;
            if (fg1 == 0) {
                fg1 = pm3;
                fg2 = pm2;
                fg3 = pm1;
                fg4 = pm0;
            }
            lg1 = pm3;
            lg2 = pm2;
            lg3 = pm1;
            lg4 = pm0;
        }
    }

    printf("%d %d %d|%d|%lld %lld %lld %lld|%lld %lld %lld %lld|\n", d0, d1, d2, count, fg1, fg2, fg3, fg4, lg1, lg2, lg3, lg4);
}

int main() {
    initialize();

    printf("differences|count|first group|last group\n");

    diff1(2);
    diff1(1);

    diff2(2, 2);
    diff2(2, 4);
    diff2(4, 2);

    diff3(6, 4, 2);

    return 0;
}


using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;

public static class SuccessivePrimeDifferences {

    public static void Main() {
        var primes = GeneratePrimes(1_000_000).ToList();
        foreach (var d in new[] {
            new [] { 2 },
            new [] { 1 },
            new [] { 2, 2 },
            new [] { 2, 4 },
            new [] { 4, 2 },
            new [] { 6, 4, 2 },
        }) {
            IEnumerable<int> first = null, last = null;
            int count = 0;
            foreach (var grp in FindDifferenceGroups(d)) {
                if (first == null) first = grp;
                last = grp;
                count++;
            }
            Console.WriteLine($"{$"({string.Join(", ", first)})"}, {$"({string.Join(", ", last)})"}, {count}");
        }

        IEnumerable<IEnumerable<int>> FindDifferenceGroups(int[] diffs) {
            for (int pi = diffs.Length; pi < primes.Count; pi++)
                if (Range(0, diffs.Length).All(di => primes[pi-diffs.Length+di+1] - primes[pi-diffs.Length+di] == diffs[di]))
                    yield return Range(pi - diffs.Length, diffs.Length + 1).Select(i => primes[i]);
        }

        IEnumerable<int> GeneratePrimes(int lmt) {
            bool[] comps = new bool[lmt + 1];
            comps[0] = comps[1] = true;
            yield return 2; yield return 3;
            for (int j = 4; j <= lmt; j += 2) comps[j] = true;
            for (int j = 9; j <= lmt; j += 6) comps[j] = true;
            int i = 5, d = 4, rt = (int)Math.Sqrt(lmt);
            for ( ; i <= rt; i += (d = 6 - d))
                if (!comps[i]) {
                    yield return i;
                    for (int j = i * i, k = i << 1; j <= lmt; j += k)
                        comps[j] = true;
                }
            for ( ; i <= lmt; i += (d = 6 - d)) if (!comps[i]) yield return i;
        }
    }
}


#include <iostream>
#include <cstdint>
#include <vector>
#include "prime_sieve.hpp"

using integer = uint32_t;
using vector = std::vector<integer>;

void print_vector(const vector& vec) {
    if (!vec.empty()) {
        auto i = vec.begin();
        std::cout << '(' << *i;
        for (++i; i != vec.end(); ++i)
            std::cout << ", " << *i;
        std::cout << ')';
    }
}

class diffs {
public:
    diffs(std::initializer_list<integer> list) : diffs_(list) {}
    diffs(const vector& vec) : diffs_(vec) {}
    void test_group(const vector&);
    size_t size() const {
        return diffs_.size();
    }
    void print(std::ostream&);
private:
    vector diffs_;
    vector first_;
    vector last_;
    integer count_ = 0;
};

void diffs::test_group(const vector& vec) {
    if (vec.size() < size() + 1)
        return;
    size_t start = vec.size() - size() - 1;
    for (size_t i = 0, j = start + 1; i < size(); ++i, ++j) {
        if (vec[j] - vec[j - 1] != diffs_[i])
            return;
    }
    vector group(vec.begin() + start, vec.end());
    if (count_ == 0)
        first_ = group;
    last_ = group;
    ++count_;
}

void diffs::print(std::ostream& out) {
    print_vector(diffs_);
    out << ": first group = ";
    print_vector(first_);
    out << ", last group = ";
    print_vector(last_);
    out << ", count = " << count_ << '\n';
}

int main() {
    const integer limit = 1000000;
    const size_t max_group_size = 4;
    prime_sieve sieve(limit);
    diffs d[] = { {2}, {1}, {2, 2}, {2, 4}, {4, 2}, {6, 4, 2} };
    vector group;
    for (integer p = 0; p < limit; ++p) {
        if (!sieve.is_prime(p))
            continue;
        if (group.size() >= max_group_size)
            group.erase(group.begin());
        group.push_back(p);
        for (auto&& diff : d) {
            diff.test_group(group);
        }
    }
    for (auto&& diff : d) {
        diff.print(std::cout);
    }
    return 0;
}


program Successive_prime_differences;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Generics.Collections;

function IsPrime(a: UInt64): Boolean;
var
  d: UInt64;
begin
  if (a < 2) then
    exit(False);

  if (a mod 2) = 0 then
    exit(a = 2);

  if (a mod 3) = 0 then
    exit(a = 3);

  d := 5;

  while (d * d <= a) do
  begin
    if (a mod d = 0) then
      Exit(false);
    inc(d, 2);

    if (a mod d = 0) then
      Exit(false);
    inc(d, 4);
  end;

  Result := True;
end;

function Primes(const limit: UInt64): TArray<UInt64>;
var
  i: UInt64;

  procedure Add(const value: UInt64);
  begin
    SetLength(result, Length(result) + 1);
    Result[Length(result) - 1] := value;
  end;

begin
  if limit < 2 then
    exit;

  // 2 is the only even prime
  Add(2);

  i := 3;
  while i <= limit do
  begin
    if IsPrime(i) then
      Add(i);
    inc(i, 2);
  end;
end;

function Commatize(const n: UInt64): string;
var
  str: string;
  digits: Integer;
  i: Integer;
begin
  Result := '';
  str := n.ToString;
  digits := str.Length;

  for i := 1 to digits do
  begin
    if ((i > 1) and (((i - 1) mod 3) = (digits mod 3))) then
      Result := Result + ',';
    Result := Result + str[i];
  end;
end;

function CheckScan(index: Integer; p: TArray<UInt64>; pattern: array of Integer): Boolean;
var
  i, last: Integer;
begin
  last := Length(pattern) - 1;
  for i := 0 to last do
    if p[index - last + i - 1] + pattern[i] <> p[index - last + i] then
      exit(False);
  Result := True;
end;

const
  GroupLabel: array[1..6] of string = ('(2)', '(1)', '(2, 2)', '(2, 4)',
    '(4, 2)', '(6, 4, 2)');

var
  limit, start: UInt64;
  c: TArray<UInt64>;
  i, j: UInt64;
  Group: array[1..6] of Tlist<string>;

begin
  for i := 1 to 6 do
    Group[i] := Tlist<string>.Create;

  limit := Trunc(1e6 - 1);
  c := Primes(limit);

  for j := 1 to High(c) do
  begin
    if CheckScan(j, c, [2]) then
      Group[1].Add(format('(%d,%d)', [c[j - 1], c[j]]));

    if CheckScan(j, c, [1]) then
      Group[2].Add(format('(%d,%d)', [c[j - 1], c[j]]));

    if j > 1 then
    begin
      if CheckScan(j, c, [2, 2]) then
        Group[3].Add(format('(%d,%d,%d)', [c[j - 2], c[j - 1], c[j]]));

      if CheckScan(j, c, [2, 4]) then
        Group[4].Add(format('(%d,%d,%d)', [c[j - 2], c[j - 1], c[j]]));

      if CheckScan(j, c, [4, 2]) then
        Group[5].Add(format('(%d,%d,%d)', [c[j - 2], c[j - 1], c[j]]));
    end;

    if j > 2 then
      if CheckScan(j, c, [6, 4, 2]) then
        Group[6].Add(format('(%d,%d,%d,%d)', [c[j - 3], c[j - 2], c[j - 1], c[j]]));

  end;

  for i := 1 to 6 do
  begin
    Write(GroupLabel[i], ': first group = ', Group[i].First);
    Writeln(', last group = ', Group[i].last, ', count = ', Group[i].Count);
    Group[i].free;
  end;

  readln;
end.


print(‘knight’[1..])
print(‘socks’[0 .< (len)-1])
print(‘brooms’[1 .< (len)-1])


// Successive primes. Nigel Galloway: May 6th., 2019
let sP n=let sP=pCache|>Seq.takeWhile(fun n->n<1000000)|>Seq.windowed(Array.length n+1)|>Seq.filter(fun g->g=(Array.scan(fun n g->n+g) g.[0] n))
         printfn "sP %A\t-> Min element = %A Max element = %A of %d elements" n (Seq.head sP) (Seq.last sP) (Seq.length sP)
List.iter sP [[|2|];[|1|];[|2;2|];[|2;4|];[|4;2|];[|6;4;2|]]


USING: formatting fry grouping kernel math math.primes
math.statistics sequences ;
IN: rosetta-code.successive-prime-differences

: seq-diff ( seq diffs -- seq' quot )
    dup [ length 1 + <clumps> ] dip '[ differences _ sequence= ]
    ; inline

: show ( seq diffs -- )
    [ "...for differences %u:\n" printf ] keep seq-diff
    [ find nip { } like ]
    [ find-last nip { } like ]
    [ count ] 2tri
    "First group: %u\nLast group: %u\nCount: %d\n\n" printf ;

: successive-prime-differences ( -- )
    "Groups of successive primes up to one million...\n" printf
    1,000,000 primes-upto {
        { 2 }
        { 1 }
        { 2 2 }
        { 2 4 }
        { 4 2 }
        { 6 4 2 }
    } [ show ] with each ;

MAIN: successive-prime-differences


*        Substring/Top and tail    04/03/2017
SUBSTRTT CSECT
         USING  SUBSTRTT,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
*
         XPRNT  S8,L'S8            print s8
         MVC    S7,S8+1            s7=substr(s8,2,7)
         XPRNT  S7,L'S7            print s7
         MVC    S7,S8              s7=substr(s8,1,7)
         XPRNT  S7,L'S7            print s7
         MVC    S6,S8+1            s6=substr(s8,2,6)
         XPRNT  S6,L'S6            print s6
*
         L      R13,4(0,R13)       epilog
         LM     R14,R12,12(R13)    restore previous context
         XR     R15,R15            rc=0
         BR     R14                exit
S8       DC     CL8'12345678'
S7       DS     CL7
S6       DS     CL6
         YREGS
         END    SUBSTRTT


(defun str-rest (str)
   (coerce (rest (coerce str 'list)) 'string))

(defun rdc (xs)
   (if (endp (rest xs))
       nil
       (cons (first xs)
             (rdc (rest xs)))))

(defun str-rdc (str)
   (coerce (rdc (coerce str 'list)) 'string))

(str-rdc "string")
(str-rest "string")
(str-rest (str-rdc "string"))


PROC Main()
  CHAR ARRAY text="qwertyuiop"
  CHAR ARRAY res(20)
  BYTE n,m

  PrintF("Original string:%E  ""%S""%E%E",text)

  SCopyS(res,text,2,text(0))
  PrintF("String without the top:%E  ""%S""%E%E",res)

  SCopyS(res,text,1,text(0)-1)
  PrintF("String without the tail:%E  ""%S""%E%E",res)

  SCopyS(res,text,2,text(0)-1)
  PrintF("String without the top and the tail:%E  ""%S""%E%E",res)
RETURN


with Ada.Text_IO;

procedure Remove_Characters is
   S: String := "upraisers";
   use Ada.Text_IO;
begin
   Put_Line("Full String:   """ & S & """");
   Put_Line("Without_First: """ & S(S'First+1 .. S'Last) & """");
   Put_Line("Without_Last:  """ & S(S'First   .. S'Last-1) & """");
   Put_Line("Without_Both:  """ & S(S'First+1 .. S'Last-1) & """");
end Remove_Characters;


#include "isprime.bas"

function nextprime( n as uinteger ) as uinteger
    'finds the next prime after n
    if n = 0 then return 2
    if n < 3 then return n + 1
    dim as integer q = n + 2
    while not isprime(q)
        q+=2
    wend
    return q
end function

function spd( byval n as integer, d() as integer ) as boolean
    if not isprime(n) then return false
    for i as integer = lbound(d) to ubound(d)
        if not nextprime(n) = n + d(i) then return false
        n+=d(i)
    next i
    return true
end function

sub print_set( byval n as uinteger, d() as uinteger )
    print "( ";n;" ";
    for i as integer = lbound(d) to ubound(d)
        print n+d(i);" ";
        n+=d(i)
    next i
    print ")"
end sub

function count_below( max as uinteger, d() as uinteger ) as uinteger
    dim as uinteger c = 0, last = 0
    for n as uinteger = 2 to max-d(ubound(d))
        if spd(n, d()) then
            c+=1
            if c=1 then print_set( n, d() )
            last = n
        end if
    next n
    print_set(last, d())
    return c
end function

dim as integer n, c

'example 1, differences of 2
redim as uinteger d(0)
d(0) = 2
print "Differences of 2 (the twin primes)"
c = count_below(1000000, d())
print "Number of occurrences: ", c

'example 2, difference of 1
d(0) = 1
print
print "Differences of 1"
c = count_below(1000000, d())
print "Number of occurrences: ", c

'example 3, differences of 2,2
redim as uinteger d(1)
d(0) = 2 : d(1) = 2
print
print "Differences of 2, 2"
c = count_below(1000000, d())
print "Number of occurrences: ", c

'example 4, differences of 2,4
d(1) = 4
print
print "Differences of 2, 4"
c = count_below(1000000, d())
print "Number of occurrences: ", c

'example 5, differences of 2,2
d(0) = 4 : d(1) = 2
print
print "Differences of 4, 2"
c = count_below(1000000, d())
print "Number of occurrences: ", c

'example 6, differences of 6,4,2
redim as uinteger d(2)
d(0) = 6 : d(1) = 4 : d(2) = 2
print
print "Differences of 6, 4, 2"
c = count_below(1000000, d())
print "Number of occurrences: ", c


o_text(delete("knights", 0));
o_newline();
o_text(delete("knights", -1));
o_newline();
o_text(delete(delete("knights", 0), -1));
o_newline();


#!/usr/local/bin/a68g --script #

STRING str="upraisers";
printf(($gl$,
  str,                      # remove no characters #
  str[LWB str+1:         ], # remove the first character #
  str[         :UPB str-1], # remove the last character #
  str[LWB str+1:UPB str-1], # remove both the first and last character #
  str[LWB str+2:         ], # remove the first 2 characters #
  str[         :UPB str-2], # remove the last 2 characters #
  str[LWB str+1:UPB str-2], # remove 1 before and 2 after #
  str[LWB str+2:UPB str-1], # remove 2 before and one after #
  str[LWB str+2:UPB str-2]  # remove both the first and last 2 characters #
))


#include <hopper.h>
#proto showmessage(_X_)
main:
  s="message", t=s
  ++s, _show message(s)
  s=t
  --s, _show message(s)
  ++s, _show message(s)
{0}return

.locals
showmessage(_S_)
  {_S_,"\n"}print
back


package main

import "fmt"

func sieve(limit int) []int {
    primes := []int{2}
    c := make([]bool, limit+1) // composite = true
    // no need to process even numbers > 2
    p := 3
    for {
        p2 := p * p
        if p2 > limit {
            break
        }
        for i := p2; i <= limit; i += 2 * p {
            c[i] = true
        }
        for {
            p += 2
            if !c[p] {
                break
            }
        }
    }
    for i := 3; i <= limit; i += 2 {
        if !c[i] {
            primes = append(primes, i)
        }
    }
    return primes
}

func successivePrimes(primes, diffs []int) [][]int {
    var results [][]int
    dl := len(diffs)
outer:
    for i := 0; i < len(primes)-dl; i++ {
        group := make([]int, dl+1)
        group[0] = primes[i]
        for j := i; j < i+dl; j++ {
            if primes[j+1]-primes[j] != diffs[j-i] {
                group = nil
                continue outer
            }
            group[j-i+1] = primes[j+1]
        }
        results = append(results, group)
        group = nil
    }
    return results
}

func main() {
    primes := sieve(999999)
    diffsList := [][]int{{2}, {1}, {2, 2}, {2, 4}, {4, 2}, {6, 4, 2}}
    fmt.Println("For primes less than 1,000,000:-\n")
    for _, diffs := range diffsList {
        fmt.Println("  For differences of", diffs, "->")
        sp := successivePrimes(primes, diffs)
        if len(sp) == 0 {
            fmt.Println("    No groups found")
            continue
        }
        fmt.Println("    First group   = ", sp[0])
        fmt.Println("    Last group    = ", sp[len(sp)-1])
        fmt.Println("    Number found  = ", len(sp))
        fmt.Println()
    }
}


String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);

// Regular Expressions approach
String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);


set aString to "This is some text"

set stringLength to (count aString) -- The number of characters in the text.

-- AppleScript indices are 1-based. Ranges can be specified in several different ways.
if (stringLength > 1) then
    set substring1 to text 2 thru stringLength of aString
    -- set substring1 to text 2 thru -1 of aString
    -- set substring1 to text 2 thru end of aString
    -- set substring1 to text from character 2 to character stringLength of aString
    -- set substring1 to aString's text from 2 to -1
    -- Some combination of the above.
else
    set substring1 to ""
end if

if (stringLength > 1) then
    set substring2 to text 1 thru -2 of aString
else
    set substring2 to ""
end if

if (stringLength > 2) then
    set substring3 to text 2 thru -2 of aString
else
    set substring3 to ""
end if

return substring1 & linefeed & substring2 & linefeed & substring3


{-# LANGUAGE NumericUnderscores #-}
import Data.Numbers.Primes (primes)

type Result = [(String, [Int])]

oneMillionPrimes :: Integral p => [p]
oneMillionPrimes = takeWhile (<1_000_000) primes

getGroups :: [Int] -> Result
getGroups [] = []
getGroups ps@(n:x:y:z:xs)
  | x-n == 6 && y-x == 4 && z-y == 2 = ("(6 4 2)", [n, x, y, z])            : getGroups (tail ps)
  | x-n == 4 && y-x == 2             = ("(4 2)", [n, x, y])                 : getGroups (tail ps)
  | x-n == 2 && y-x == 4             = ("(2 4)", [n, x, y]) : ("2", [n, x]) : getGroups (tail ps)
  | x-n == 2 && y-x == 2             = ("(2 2)", [n, x, y]) : ("2", [n, x]) : getGroups (tail ps)
  | x-n == 2                         = ("2", [n, x])                        : getGroups (tail ps)
  | x-n == 1                         = ("1", [n, x])                        : getGroups (tail ps)
  | otherwise                        = getGroups (tail ps)
getGroups (x:xs) = getGroups xs

groups :: Result
groups = getGroups oneMillionPrimes

showGroup :: String -> IO ()
showGroup group = do
  putStrLn $ "Differences of " ++ group ++ ": " ++ show (length r)
  putStrLn $ "First: " ++ show (head r) ++ "\nLast:  " ++ show (last r) ++ "\n"
  where r = foldr (\(a, b) c -> if a == group then b : c else c) [] groups

main :: IO ()
main = showGroup "2" >> showGroup "1" >> showGroup "(2 2)" >> showGroup "(2 4)" >> showGroup "(4 2)"
  >> showGroup "(6 4 2)"


knight: "knight"
socks: "socks"
brooms: "brooms"

print drop knight 1                     ; strip first character
print slice knight 1 (size knight)-1    ; alternate way to strip first character

print chop socks                        ; strip last character
print take socks (size socks)-1         ; alternate way to strip last character
print slice socks 0 (size socks)-2      ; yet another way to strip last character

print chop drop brooms 1                ; strip both first and last characters
print slice brooms 1 (size brooms)-2    ; alternate way to strip both first and last characters


myString := "knights"
MsgBox % SubStr(MyString, 2)
MsgBox % SubStr(MyString, 1, StrLen(MyString)-1)
MsgBox % SubStr(MyString, 2, StrLen(MyString)-2)


BEGIN {
  mystring="knights"
  print substr(mystring,2)                       # remove the first letter
  print substr(mystring,1,length(mystring)-1)    # remove the last character
  print substr(mystring,2,length(mystring)-2)    # remove both the first and last character
}


   primes_less_than=: i.&.:(p:inv)
   assert 2 3 5 -: primes_less_than 7
   Primes=: primes_less_than 1e6

   NB. Insert minus `-/' into the length two infixes `\'.
   NB. Passive `~' swaps the arguments producing the positive differences.
   Successive_Differences=: 2 -~/\ Primes
   assert 8169 -: +/ 2 = Successive_Differences   NB. twin prime tally

   Groups=: 2 ; 1 ; 2 2 ; 2 4 ; 4 2 ; 6 4 2

   group_index=: [: I. E.
   end_groups=: Primes {~  ({. , {:)@] +/ 0,#\@[

   Header=: <;._2 'Group;Count;First/Last groups;'

   Header ,> Groups ([ ([ ; #@] ; end_groups) group_index)&.> <Successive_Differences
┌─────┬─────┬───────────────────────────┐
│Group│Count│First/Last groups          │
├─────┼─────┼───────────────────────────┤
│2    │8169 │     3      5              │
│     │     │999959 999961              │
├─────┼─────┼───────────────────────────┤
│1    │1    │2 3                        │
│     │     │2 3                        │
├─────┼─────┼───────────────────────────┤
│2 2  │1    │3 5 7                      │
│     │     │3 5 7                      │
├─────┼─────┼───────────────────────────┤
│2 4  │1393 │     5      7     11       │
│     │     │999431 999433 999437       │
├─────┼─────┼───────────────────────────┤
│4 2  │1444 │     7     11     13       │
│     │     │997807 997811 997813       │
├─────┼─────┼───────────────────────────┤
│6 4 2│306  │    31     37     41     43│
│     │     │997141 997147 997151 997153│
└─────┴─────┴───────────────────────────┘


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SuccessivePrimeDifferences {
    private static Integer[] sieve(int limit) {
        List<Integer> primes = new ArrayList<>();
        primes.add(2);
        boolean[] c = new boolean[limit + 1];// composite = true
        // no need to process even numbers > 2
        int p = 3;
        while (true) {
            int p2 = p * p;
            if (p2 > limit) {
                break;
            }
            for (int i = p2; i <= limit; i += 2 * p) {
                c[i] = true;
            }
            do {
                p += 2;
            } while (c[p]);
        }
        for (int i = 3; i <= limit; i += 2) {
            if (!c[i]) {
                primes.add(i);
            }
        }

        return primes.toArray(new Integer[0]);
    }

    private static List<List<Integer>> successivePrimes(Integer[] primes, Integer[] diffs) {
        List<List<Integer>> results = new ArrayList<>();
        int dl = diffs.length;
        outer:
        for (int i = 0; i < primes.length - dl; i++) {
            Integer[] group = new Integer[dl + 1];
            group[0] = primes[i];
            for (int j = i; j < i + dl; ++j) {
                if (primes[j + 1] - primes[j] != diffs[j - i]) {
                    continue outer;
                }
                group[j - i + 1] = primes[j + 1];
            }
            results.add(Arrays.asList(group));
        }
        return results;
    }

    public static void main(String[] args) {
        Integer[] primes = sieve(999999);
        Integer[][] diffsList = {{2}, {1}, {2, 2}, {2, 4}, {4, 2}, {6, 4, 2}};
        System.out.println("For primes less than 1,000,000:-\n");
        for (Integer[] diffs : diffsList) {
            System.out.printf("  For differences of %s ->\n", Arrays.toString(diffs));
            List<List<Integer>> sp = successivePrimes(primes, diffs);
            if (sp.isEmpty()) {
                System.out.println("    No groups found");
                continue;
            }
            System.out.printf("    First group   = %s\n", Arrays.toString(sp.get(0).toArray(new Integer[0])));
            System.out.printf("    Last group    = %s\n", Arrays.toString(sp.get(sp.size() - 1).toArray(new Integer[0])));
            System.out.printf("    Number found  = %d\n", sp.size());
            System.out.println();
        }
    }
}


10 PRINT FN F$("KNIGHTS"): REM STRIP THE FIRST LETTER
20 PRINT FN L$("SOCKS"): REM STRIP THE LAST LETTER
30 PRINT FN B$("BROOMS"): REM STRIP BOTH THE FIRST AND LAST LETTER
100 END

9000 DEF FN F$(A$)=RIGHT$(A$,LEN(A$)-1)
9010 DEF FN L$(A$)=LEFT$(A$,LEN(A$)-1)
9020 DEF FN B$(A$)=FN L$(FN F$(A$))


  str ← "substring"
"substring"
  1↓str
"ubstring"
  ¯1↓str
"substrin"
  1↓¯1↓str
"ubstrin"


      s$ = "Rosetta Code"
      PRINT MID$(s$, 2)
      PRINT LEFT$(s$)
      PRINT LEFT$(MID$(s$, 2))


(substringUTF-8=
  @( Δημοτική
   : (%?a&utf$!a) ?"String with first character removed"
   )
& @( Δημοτική
   : ?"String with last character removed" (?z&utf$!z)
   )
& @( Δημοτική
   :   (%?a&utf$!a)
       ?"String with both the first and last characters removed"
       (?z&utf$!z)
   )
&   out
  $ ("String with first character removed:" !"String with first character removed")
&   out
  $ ("String with last character removed:" !"String with last character removed")
&   out
  $ ( "String with both the first and last characters removed:"
      !"String with both the first and last characters removed"
    ));


# Emit a stream of consecutive primes.
# The stream is unbounded if . is null or infinite,
# otherwise it continues up to but excluding `.`.
def primes:
  (if . == null then infinite else . end) as $n
  | 2, (range(3; $n; 2) | select(is_prime));

# s is a stream
# $deltas is an array
# Output: a stream of arrays, each corresponding to a selection of consecutive
# items from s satisfying the differences requirement.
def filter_differences(s; $deltas):

  def diffs_equal: # i.e. equal to $deltas
    . as $in
    | all( range(1;length);
           ($in[.] - $in[.-1]) == $deltas[. - 1]);

  ($deltas|length + 1) as $n
  | foreach s as $x ( {};
      .emit = null
      | .tuple += [$x]
      | .tuple |= .[-$n:]
      | if (.tuple|length) == $n
        then if (.tuple|diffs_equal) then .emit = .tuple
             else .
	     end
	else .
	end;
      select(.emit).emit );

def report_first_last_count(s):
  null | {first,last,count}
  | reduce s as $x (.;
      if .first == null then .first = $x else . end
      | .count = .count + 1
      | .last = $x ) ;


using Primes

function filterdifferences(deltas, N)
    allprimes = primes(N)
    differences = map(i -> allprimes[i + 1] - allprimes[i], 1:length(allprimes) - 1)
    println("Diff Sequence   Count         First           Last")
    for delt in deltas
        ret = trues(length(allprimes) - length(delt))
        for j in 1:length(ret)
            for (i, d) in enumerate(delt)
                if differences[j - 1 + i] != d
                    ret[j] = false
                    break
                end
            end
        end
        count, p1, pn, n = sum(ret), findfirst(ret), findlast(ret), length(delt)
        println(rpad(string(delt), 16), lpad(count, 4),
            lpad(string(allprimes[p1:p1 + n]), 18), "...", rpad(allprimes[pn:pn+n], 15))
    end
end

filterdifferences([[2], [1], [2, 2], [2, 4], [4, 2], [6, 4, 2]], 1000000)


function findspds(primelist, diffs)
  local results = {}
  for i = 1, #primelist-#diffs do
    result = {primelist[i]}
    for j = 1, #diffs do
      if primelist[i+j] - primelist[i+j-1] == diffs[j] then
        result[j+1] = primelist[i+j]
      else
        result = nil
        break
      end
    end
    results[#results+1] = result
  end
  return results
end

primegen:generate(nil, 1000000)
for _,diffs in ipairs{{2}, {1}, {2,2}, {2,4}, {4,2}, {6,4,2}} do
  spdlist = findspds(primegen.primelist, diffs)
  print("DIFFS: ["..table.concat(diffs," ").."]")
  print("COUNT: "..#spdlist)
  print("FIRST: ["..table.concat(spdlist[1]," ").."]")
  print("LAST : ["..table.concat(spdlist[#spdlist]," ").."]")
  print()
end


blsq ) "RosettaCode"[-
"osettaCode"
blsq ) "RosettaCode"-]
'R
blsq ) "RosettaCode"~]
"RosettaCod"
blsq ) "RosettaCode"[~
'e
blsq ) "RosettaCode"~-
"osettaCod"


#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main( int argc, char ** argv ){
  const char * str_a = "knight";
  const char * str_b = "socks";
  const char * str_c = "brooms";

  char * new_a = malloc( strlen( str_a ) - 1 );
  char * new_b = malloc( strlen( str_b ) - 1 );
  char * new_c = malloc( strlen( str_c ) - 2 );

  strcpy( new_a, str_a + 1 );
  strncpy( new_b, str_b, strlen( str_b ) - 1 );
  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );

  printf( "%s\n%s\n%s\n", new_a, new_b, new_c );

  free( new_a );
  free( new_b );
  free( new_c );

  return 0;
}


using System;

class Program
{
    static void Main(string[] args)
    {
        string testString = "test";
        Console.WriteLine(testString.Substring(1));
        Console.WriteLine(testString.Substring(0, testString.Length - 1));
        Console.WriteLine(testString.Substring(1, testString.Length - 2));
    }
}


private fun sieve(limit: Int): Array<Int> {
    val primes = mutableListOf<Int>()
    primes.add(2)
    val c = BooleanArray(limit + 1) // composite = true
    // no need to process even numbers > 2
    var p = 3
    while (true) {
        val p2 = p * p
        if (p2 > limit) {
            break
        }
        var i = p2
        while (i <= limit) {
            c[i] = true
            i += 2 * p
        }
        do {
            p += 2
        } while (c[p])
    }
    var i = 3
    while (i <= limit) {
        if (!c[i]) {
            primes.add(i)
        }
        i += 2
    }
    return primes.toTypedArray()
}

private fun successivePrimes(primes: Array<Int>, diffs: Array<Int>): List<List<Int>> {
    val results = mutableListOf<List<Int>>()
    val dl = diffs.size
    outer@ for (i in 0 until primes.size - dl) {
        val group = IntArray(dl + 1)
        group[0] = primes[i]
        for (j in i until i + dl) {
            if (primes[j + 1] - primes[j] != diffs[j - i]) {
                continue@outer
            }
            group[j - i + 1] = primes[j + 1]
        }
        results.add(group.toList())
    }
    return results
}

fun main() {
    val primes = sieve(999999)
    val diffsList = arrayOf(
        arrayOf(2),
        arrayOf(1),
        arrayOf(2, 2),
        arrayOf(2, 4),
        arrayOf(4, 2),
        arrayOf(6, 4, 2)
    )
    println("For primes less than 1,000,000:-\n")
    for (diffs in diffsList) {
        println("  For differences of ${diffs.contentToString()} ->")
        val sp = successivePrimes(primes, diffs)
        if (sp.isEmpty()) {
            println("    No groups found")
            continue
        }
        println("    First group   = ${sp[0].toTypedArray().contentToString()}")
        println("    Last group    = ${sp[sp.size - 1].toTypedArray().contentToString()}")
        println("    Number found  = ${sp.size}")
        println()
    }
}


#include <string>
#include <iostream>

int main( ) {
   std::string word( "Premier League" ) ;
   std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
   std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
   std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
   return 0 ;
}


; using substring:
user=> (subs "knight" 1)
"night"
user=> (subs "socks" 0 4)
"sock"
user=> (.substring "brooms" 1 5)
"room"

; using rest and drop-last:
user=> (apply str (rest "knight"))
"night"
user=> (apply str (drop-last "socks"))
"sock"
user=> (apply str (rest (drop-last "brooms")))
"room"


       identification division.
       program-id. toptail.

       data division.
       working-storage section.
       01 data-field.
          05 value "[this is a test]".

       procedure division.
       sample-main.
       display data-field
      *> Using reference modification, which is (start-position:length)
       display data-field(2:)
       display data-field(1:length of data-field - 1)
       display data-field(2:length of data-field - 2)
       goback.
       end program toptail.


ClearAll[Primediffs]
p = Prime[Range[PrimePi[10^6]]];
Primediffs[seq_] := {First[#], Last[#], Length[#]} &[p[[#1 ;; #2 + 1]] & @@@ SequencePosition[Differences[p], seq]]
Primediffs[{2}]
Primediffs[{1}]
Primediffs[{2, 2}]
Primediffs[{2, 4}]
Primediffs[{4, 2}]
Primediffs[{6, 4, 2}]


import math, strutils

const N = 1_000_000

var comp: array[2..(N - 1), bool]   # True is composite, so default is prime.
for n in 2..<N:
  if not comp[n]:
    for k in countup(n * n, N - 1, n):
      comp[k] = true

var primes = @[2]
for n in countup(3, N - 1, 2):
  if not comp[n]:
    primes.add n

iterator groups(primes: seq[int]; diffs: varargs[int]): seq[int] =
  ## Yield groups of successive primes with given differences.
  var cumdiffs = cumsummed(diffs)   # Compute differences from first prime of group.
  let groupSize = diffs.len + 1
  for i in 0..(primes.len - groupSize):
    let p = primes[i]
    var group = @[p]
    for k, diff in cumdiffs:
      if primes[i + k + 1] != p + diff: break
      group.add p + diff
    if group.len == groupSize:
      yield group

proc findGroups(primes: seq[int]; diffs: varargs[int]) =
  ## In the given list of primes and for the given differences,
  ## find the first group, the last group and the count of groups.
  var
    first, last: seq[int]
    count = 0
  for group in primes.groups(diffs):
    if first.len == 0: first = group
    last = group
    inc count
  echo "Differences: ", diffs.join(", ")
  echo "– first: ($#)" % first.join(", ")
  echo "– last:  ($#)" % last.join(", ")
  echo "– count: ", count
  echo()

primes.findGroups(2)
primes.findGroups(1)
primes.findGroups(2, 2)
primes.findGroups(2, 4)
primes.findGroups(4, 2)
primes.findGroups(6, 4, 2)


use strict;
use warnings;
use List::EachCons;
use Array::Compare;
use ntheory 'primes';

my $limit = 1E6;
my @primes = (2, @{ primes($limit) });
my @intervals = map { $primes[$_] - $primes[$_-1] } 1..$#primes;

print "Groups of successive primes <= $limit\n";

my $c = Array::Compare->new;
for my $diffs ([2], [1], [2,2], [2,4], [4,2], [6,4,2]) {
    my $n = -1;
    my @offsets = grep {$_} each_cons @$diffs, @intervals, sub { $n++; $n if $c->compare(\@_, \@$diffs) };
    printf "%10s has %5d sets: %15s … %s\n",
       '(' . join(' ',@$diffs) . ')',
        scalar @offsets,
        join(' ', @primes[$offsets[ 0]..($offsets[ 0]+@$diffs)]),
        join(' ', @primes[$offsets[-1]..($offsets[-1]+@$diffs)]);
}


> (defvar *str* "∀Ꮺ✤Л◒")
*STR*
> (subseq *str* 1) ; remove first character
"Ꮺ✤Л◒"
> (subseq *str* 0 (1- (length *str*))) ; remove last character
"∀Ꮺ✤Л"
> (subseq *str* 1 (1- (length *str*))) ; remove first and last character
"Ꮺ✤Л"


import std.stdio;

void main() {
    // strip first character
    writeln("knight"[1 .. $]);

    // strip last character
    writeln("socks"[0 .. $ - 1]);

    // strip both first and last characters
    writeln("brooms"[1 .. $ - 1]);
}


program TopAndTail;

{$APPTYPE CONSOLE}

const
  TEST_STRING = '1234567890';
begin
  Writeln(TEST_STRING);                                    // full string
  Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING)));      // first character removed
  Writeln(Copy(TEST_STRING, 1, Length(TEST_STRING) - 1));  // last character removed
  Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING) - 2));  // first and last characters removed

  Readln;
end.


with javascript_semantics
constant primes = get_primes_le(1_000_000)
procedure test(sequence differences)
    sequence res = {}
    integer ld = length(differences)
    for i=1 to length(primes)-ld do
        integer pi = primes[i]
        for j=1 to ld do
            pi += differences[j]
            if pi!=primes[i+j] then
                pi = 0
                exit
            end if
        end for
        if pi!=0 then
            res = append(res,primes[i..i+ld])
        end if
    end for
    res = {differences,length(res),res[1],res[$]}
    printf(1,"%8V : %8d %14V...%V\n",res)
end procedure

printf(1,"Differences   Count          First   Last\n")
papply({{2},{1},{2,2},{2,4},{4,2},{6,4,2}},test)


main =>
  Num is 1_000_000,
  statistics(runtime,[Start|_]),
  PrimeList = primes(Num),
  NumPrimes = PrimeList.len,
  statistics(runtime,[Stop|_]),
  RunTime = Stop - Start,
  printf("There are %w primes until %w [time(ms) %w]%n",NumPrimes, Num, RunTime),
  DiffList = [[1], [2], [2,2], [2,4], [4,2], [2,4,6],
              [2,6,4], [4,2,6], [4,6,2], [6,2,4], [6,4,2],[6,4,2,4]],
  run(DiffList, PrimeList).

primesByDiffs([],_,[]).
primesByDiffs([Prime|Primes], Diff, [Slide|Slides]):-
  Slide = new_list(Diff.len+1),
  append(Slide, _, [Prime|Primes]),
  select(Diff, Slide),!,
  primesByDiffs(Primes, Diff, Slides).
primesByDiffs([_|Primes], Diff, Slides):-
  primesByDiffs(Primes, Diff, Slides).

select([],_).
select([Diff|Diffs],[S1, S2|Stail]):-
  S2 = S1 + Diff,
  select(Diffs, [S2|Stail]).

run([],_).
run([Diff|Dtail], PrimeList):-
  statistics(runtime,[Start|_]),
  primesByDiffs(PrimeList, Diff, SlideList),
  Num = SlideList.len,
  statistics(runtime,[Stop|_]),
  Runtime = Stop - Start,
  printf("%-10w number: %5w (%2wms) first: %-22w last: %-22w\n", Diff, Num, Runtime, SlideList.first, SlideList.last),
  !,
  run(Dtail, PrimeList).


#import <Foundation/Foundation.h>

int main()
  autoreleasepool

    s := 'knight'
    Log( '%@', s[1 .. s.length-1] )  // strip first character

    s = 'socks'
    Log( '%@', s[0 .. s.length-2] )  // strip last character

    s = 'brooms'
    Log( '%@', s[1 .. s.length-2] )  // strip both first and last characters

    s = 'Δημοτική'
    Log( '%@', s[1 .. s.length-2] )  // strip both first and last characters

  return 0


import extensions;

public program()
{
    var testString := "test";

    console.printLine(testString.Substring(1));
    console.printLine(testString.Substring(0, testString.Length - 1));
    console.printLine(testString.Substring(1, testString.Length - 2))
}


iex(1)> str = "abcdefg"
"abcdefg"
iex(2)> String.slice(str, 1..-1)
"bcdefg"
iex(3)> String.slice(str, 0..-2)
"abcdef"
iex(4)> String.slice(str, 1..-2)
"bcdef"


prime(2).     % use swi prolog
prime(N):-
	N /\ 1 > 0,              % odd
	M is floor(sqrt(N)) - 1, % reverse 2*I+1
	Max is M // 2,           % integer division
	forall(between(1, Max, I), N mod (2*I+1) > 0).

primesByDiffs([],_,[]).
primesByDiffs([Prime|Primes], Diff, [Slide|Slides]):-
	length(Diff, Len0),
	Len is Len0 + 1,
	length(Slide, Len),
	append(Slide, _, [Prime|Primes]),
	select(Diff, Slide),!,
	primesByDiffs(Primes, Diff, Slides).
primesByDiffs([_|Primes], Diff, Slides):-
	primesByDiffs(Primes, Diff, Slides).

select([],_).
select([Diff|Diffs],[S1, S2|Stail]):-
	S2 is S1 + Diff,
	select(Diffs, [S2|Stail]).

run([],_).
run([Diff|Dtail], PrimeList):-
	statistics(runtime,[Start|_]),
	primesByDiffs(PrimeList, Diff, SlideList),
	length(SlideList, Num),
	statistics(runtime,[Stop|_]),
	Runtime is Stop - Start,
	SlideList = [First|SlideTail],
	format('~|~w~t~7+ number: ~|~t~d~4+ [time(ms) ~|~t~d~3+] first: ~|~w~t~22+',[Diff, Num, Runtime, First]),
	writeLast(SlideTail),!, nl,
	run(Dtail, PrimeList).

writeLast([]).
writeLast(SlideTail):-
	last(SlideTail, Last),
	format('last: ~w',[Last]).

do:-	Num is 1000000,
	statistics(runtime,[Start|_]),
	numlist(2, Num, List),
	include(prime, List, PrimeList),
	length(PrimeList, NumPrimes),
	statistics(runtime,[Stop|_]),
	RunTime is Stop - Start,
	format('there are ~w primes until ~w [time(ms) ~w]~n',[NumPrimes, Num, RunTime]),
	DiffList = [[1], [2], [2,2], [2,4], [4,2], [2,4,6],
		    [2,6,4], [4,2,6], [4,6,2], [6,2,4], [6,4,2]],
	run(DiffList, PrimeList).


(let ((string "top and tail"))
  (substring string 1) ;=> "op and tail"
  (substring string 0 (1- (length string))) ;=> "top and tai"
  (substring string 1 (1- (length string)))) ;=> "op and tai"


1> Str = "Hello".
"Hello"
2> string:sub_string(Str, 2).                   % To strip the string from the right by 1
"ello"
3> string:sub_string(Str, 1, length(Str)-1).    % To strip the string from the left by 1
"Hell"
4> string:sub_string(Str, 2, length(Str)-1).    % To strip the string from both sides by 1
"ell"


function strip_first(sequence s)
    return s[2..$]
end function

function strip_last(sequence s)
    return s[1..$-1]
end function

function strip_both(sequence s)
    return s[2..$-1]
end function

puts(1, strip_first("knight"))  -- strip first character
puts(1, strip_last("write"))    -- strip last character
puts(1, strip_both("brooms"))   -- strip both first and last characters


# https://docs.sympy.org/latest/index.html
from sympy import Sieve

def nsuccprimes(count, mx):
    "return tuple of <count> successive primes <= mx (generator)"
    sieve = Sieve()
    sieve.extend(mx)
    primes = sieve._list
    return zip(*(primes[n:] for n in range(count)))

def check_value_diffs(diffs, values):
    "Differences between successive values given by successive items in diffs?"
    return all(v[1] - v[0] == d
               for d, v in zip(diffs, zip(values, values[1:])))

def successive_primes(offsets=(2, ), primes_max=1_000_000):
    return (sp for sp in nsuccprimes(len(offsets) + 1, primes_max)
            if check_value_diffs(offsets, sp))

if __name__ == '__main__':
    for offsets, mx in [((2,),      1_000_000),
                        ((1,),      1_000_000),
                        ((2, 2),    1_000_000),
                        ((2, 4),    1_000_000),
                        ((4, 2),    1_000_000),
                        ((6, 4, 2), 1_000_000),
                       ]:
        print(f"## SETS OF {len(offsets)+1} SUCCESSIVE PRIMES <={mx:_} WITH "
              f"SUCCESSIVE DIFFERENCES OF {str(list(offsets))[1:-1]}")
        for count, last in enumerate(successive_primes(offsets, mx), 1):
            if count == 1:
                first = last
        print("  First group:", str(first)[1:-1])
        print("   Last group:", str(last)[1:-1])
        print("        Count:", count)


[<EntryPoint>]
let main args =
    let s = "一二三四五六七八九十"
    printfn "%A" (s.Substring(1))
    printfn "%A" (s.Substring(0, s.Length - 1))
    printfn "%A" (s.Substring(1, s.Length - 2))
    0


USING: io kernel sequences ;
"Rosetta code" [ rest ] [ but-last ] [ rest but-last ] tri
[ print ] [email protected]


: hello ( -- c-addr u )
  s" Hello" ;

hello 1 /string type     \ => ello

hello 1- type            \ => hell

hello 1 /string 1- type  \ => ell


program substring

  character(len=5) :: string
  string = "Hello"

  write (*,*) string
  write (*,*) string(2:)
  write (*,*) string( :len(string)-1)
  write (*,*) string(2:len(string)-1)

end program substring


Deque[Int] s
V seed = 292929

s.append(seed)
s.append(1)

L(n) 2..54
   s.append((s[n - 2] - s[n - 1]) % 10 ^ 9)

Deque[Int] r
L(n) 55
   V i = (34 * (n + 1)) % 55
   r.append(s[i])

F py_mod(a, b)
   R ((a % b) + b) % b

F getnextr()
   :r.append(py_mod((:r[0] - :r[31]), 10 ^ 9))
   :r.pop_left()
   R :r[54]

L 0 .< 219 - 54
   getnextr()

L 5
   print(‘result = ’getnextr())


use Math::Primesieve;
my $sieve = Math::Primesieve.new;

my $max = 1_000_000;
my @primes = $sieve.primes($max);
my $filter = @primes.Set;
my $primes = @primes.categorize: &successive;

sub successive ($i) {
    gather {
        take '2' if $filter{$i + 2};
        take '1' if $filter{$i + 1};
        take '2_2' if all($filter{$i «+« (2,4)});
        take '2_4' if all($filter{$i «+« (2,6)});
        take '4_2' if all($filter{$i «+« (4,6)});
        take '6_4_2' if all($filter{$i «+« (6,10,12)}) and
            none($filter{$i «+« (2,4,8)});
    }
}

sub comma { $^i.flip.comb(3).join(',').flip }

for (2,), (1,), (2,2), (2,4), (4,2), (6,4,2) -> $succ {
    say "## Sets of {1+$succ} successive primes <= { comma $max } with " ~
        "successive differences of { $succ.join: ', ' }";
    my $i = $succ.join: '_';
    for 'First', 0, ' Last', * - 1 -> $where, $ind {
        say "$where group: ", join ', ', [\+] flat $primes{$i}[$ind], |$succ
    }
    say '      Count: ', +$primes{$i}, "\n";
}


' FB 1.05.0 Win64

Dim s As String  = "panda"
Dim s1 As String = Mid(s, 2)
Dim s2 As String = Left(s, Len(s) - 1)
Dim s3 As String = Mid(s, 2, Len(s) - 2)
Print s
Print s1
Print s2
Print s3
Sleep


package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    // ASCII contents:  Interpreting "characters" as bytes.
    s := "ASCII"
    fmt.Println("String:                ", s)
    fmt.Println("First byte removed:    ", s[1:])
    fmt.Println("Last byte removed:     ", s[:len(s)-1])
    fmt.Println("First and last removed:", s[1:len(s)-1])
    // UTF-8 contents:  "Characters" as runes (unicode code points)
    u := "Δημοτική"
    fmt.Println("String:                ", u)
    _, sizeFirst := utf8.DecodeRuneInString(u)
    fmt.Println("First rune removed:    ", u[sizeFirst:])
    _, sizeLast := utf8.DecodeLastRuneInString(u)
    fmt.Println("Last rune removed:     ", u[:len(u)-sizeLast])
    fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}


package Subtractive_Generator is
   type State is private;
   procedure Initialize (Generator : in out State; Seed : Natural);
   procedure Next (Generator : in out State; N : out Natural);
private
   type Number_Array is array (Natural range <>) of Natural;
   type State is record
      R    : Number_Array (0 .. 54);
      Last : Natural;
   end record;
end Subtractive_Generator;


/*REXX program finds and displays  primes  with successive differences  (up to a limit).*/
parse arg H . 1 . difs                           /*allow the highest number be specified*/
if H=='' | H==","  then  H= 1000000              /*Not specified?  Then use the default.*/
if difs=''   then  difs= 2 1 2.2 2.4 4.2 6.4.2   /* "      "         "   "   "     "    */
call genP H

        do j=1  for words(difs)                             /*traipse through the lists.*/
        dif= translate( word(difs, j),,.);  dw= words(dif)  /*obtain true differences.  */
            do i=1  for dw;  dif.i= word(dif, i)            /*build an array of diffs.  */
            end   /*i*/                                     /* [↑]  for optimization.   */
        say center('primes with differences of:'  dif,  50, '─')        /*display title.*/
        p= 1;                        c= 0;        grp=      /*init. prime#,  count, grp.*/
             do a=1;  p= nextP(p+1);  if p==0  then leave   /*find the next  DIF  primes*/
             aa= p;   !.=                                   /*AA: nextP;  the group #'s.*/
             !.1= p                                         /*assign 1st prime in group.*/
                    do g=2  for dw                          /*get the rest of the group.*/
                    aa= nextP(aa+1); if aa==0  then leave a /*obtain the next prime.    */
                    !.g= aa;         _= g-1                 /*prepare to add difference.*/
                    if !._ + dif._\==!.g  then iterate a    /*determine if fits criteria*/
                    end   /*g*/
             c= c+1                                         /*bump count of # of groups.*/
             grp= !.1;       do b=2  for dw;  grp= grp !.b  /*build a list of primes.   */
                             end   /*b*/
             if c==1  then say '     first group: '   grp   /*display the first group.  */
             end   /*a*/
                                                            /* [↓]  test if group found.*/
        if grp==''   then say "         (none)"             /*display the  last group.  */
                     else say '      last group: '   grp    /*   "     "     "    "     */
                          say '           count: '   c      /*   "     "  group count.  */
        say
        end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
nextP:    do nxt=arg(1)  to H;  if @.nxt==.  then return nxt;  end /*nxt*/;     return 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: procedure expose @.; parse arg N;  != 0;  @.=.;  @.1=      /*initialize the array.*/
          do e=4  by 2  for (N-1)%2;  @.e=;  end /*treat the even integers > 2  special.*/
                                                 /*all primes are indicated with a  "." */
        do j=1  by 2  for (N-1)%2                /*use odd integers up to  N  inclusive.*/
        if @.j==.  then do;  if !  then iterate  /*Prime?   Should skip the top part ?  */
                             jj= j * j           /*compute the square of  J.        ___ */
                             if jj>N  then != 1  /*indicate skip top part  if  j > √ N  */
                               do m=jj  to N  by j+j;  @.m=;  end       /*odd multiples.*/
                        end                      /* [↑]  strike odd multiples  ¬ prime. */
        end   /*j*/;               return


10 A$="knight":B$="socks":C$="brooms"
20 PRINT MID$(A$,2)
30 PRINT LEFT$(B$,LEN(B$)-1)
40 PRINT MID$(C$,2,LEN(C$)-2)


-- We define the functions to return an empty string if the argument is too
-- short for the particular operation.

remFirst, remLast, remBoth :: String -> String

remFirst "" = ""
remFirst cs = tail cs

remLast "" = ""
remLast cs = init cs

remBoth (c:cs) = remLast cs
remBoth  _     = ""

main :: IO ()
main = do
  let s = "Some string."
  mapM_ (\f -> putStrLn . f $ s) [remFirst, remLast, remBoth]


#include<stdio.h>

#define MOD 1000000000
int state[55], si = 0, sj = 0;

int subrand();

void subrand_seed(int p1)
{
	int i, j, p2 = 1;

	state[0] = p1 % MOD;
	for (i = 1, j = 21; i < 55; i++, j += 21) {
		if (j >= 55) j -= 55;
		state[j] = p2;
		if ((p2 = p1 - p2) < 0) p2 += MOD;
		p1 = state[j];
	}
	si = 0;
	sj = 24;
	for (i = 0; i < 165; i++) subrand();
}

int subrand()
{
	int x;
	if (si == sj) subrand_seed(0);

	if (!si--) si = 54;
	if (!sj--) sj = 54;
	if ((x = state[si] - state[sj]) < 0) x += MOD;

	return state[si] = x;
}

int main()
{
	subrand_seed(292929);
	int i;
	for (i = 0; i < 10; i++) printf("%d\n", subrand());

	return 0;
}


load "stdlib.ring"
see "working..." + nl + nl
see "For primes less than 1,000,000:" + nl + nl
num = 0
limit = 1000000
Primes = []
SuccPrimes = []
Sp = [[2],[1],[2,2],[2,4],[4,2],[6,4,2]]

for n = 1 to limit
    if isprime(n)
       add(Primes,n)
    ok
next

for n = 1 to len(Sp)
    num = 0
    for m = 1 to len(Primes)-len(Sp[n])
        flag = 0
        SuccPrimes = []
        for p = 1 to len(Sp[n])
            if (Primes[m+p]-Primes[m+p-1] = Sp[n][p])
               flag++
               add(SuccPrimes,Primes[m+p])
               add(SuccPrimes,Primes[m+p-1])
            else
               exit
            ok
        next

        SuccPrimes = sort(SuccPrimes)
        for x = len(SuccPrimes) to 2 step -1
            if SuccPrimes[x] = SuccPrimes[x-1]
               del(SuccPrimes,x)
            ok
        next

        if len(SuccPrimes) = len(Sp[n])+1
           num++
           LastSuccPrimes = SuccPrimes
           if num = 1
              see "For differences of "
              showArray(Sp[n])
              see " ->" + nl
              see " First group = "
              showArray(SuccPrimes)
              see nl
           ok
        ok
    next
    see " Last group = "
    showArray(LastSuccPrimes)
    see nl
    see " Number found = " + num + nl + nl
 next

see "done..." + nl

func showArray(array)
     txt = ""
     see "["
     for n = 1 to len(array)
         txt = txt + array[n] + ","
     next
     txt = left(txt,len(txt)-1)
     txt = txt + "]"
     see txt


require 'prime'
PRIMES = Prime.each(1_000_000).to_a
difs = [[2], [1], [2,2], [2,4], [4,2], [6,4,2]]

difs.each do |ar|
  res = PRIMES.each_cons(ar.size+1).select do |slice|
    slice.each_cons(2).zip(ar).all? {|(a,b), c| a+c == b}
  end
  puts "#{ar} has #{res.size} sets. #{res.first}...#{res.last}"
end


fn is_prime(num: u32) -> bool {
  match num {
      x if x < 4 => x > 1,
      x if x % 2 == 0 => false,
      x => { let limit = (x as f32).sqrt().ceil() as u32;
              (3..=limit).step_by(2).all(|a| x % a != 0)
            }
  }
}

fn primes_by_diffs(primes: &[u32], diffs: &[u32]) -> Vec<Vec<u32>> {

  fn select(diffs: &[u32], prime_win: &[u32], acc: bool) -> bool {
    if diffs.is_empty() || !acc {
      acc
    }
    else {
      let acc1 = prime_win[0] + diffs[0] == prime_win[1];
      select(&diffs[1..], &prime_win[1..], acc1)
    }
  }

  primes.windows(diffs.len() + 1)
        .filter(|&win| select(diffs, win, true))
        .map(|win| win.to_vec())
        .collect()
}

fn main() {
  let limit = 1_000_000u32;
  let start = std::time::Instant::now();
  let primes = (2..).filter(|&i| is_prime(i));
  let prime_list: Vec<u32> = primes.take_while(|&p| p <= limit).collect();
  let duration = start.elapsed();
  println!("primes time: {:?}", duration);
  for diffs in vec!(vec!(1), vec!(2), vec!(2,2), vec!(2,4), vec!(4,2), vec!(6,4,2), vec!(2,4,6)) {
    let result_list = primes_by_diffs(&prime_list, &diffs);
    let len = result_list.len();
    println!("{:?} number: {}\n\tfirst: {:?}", diffs, len, result_list[0]);
    if len == 1 {
      println!()
    }
    if len > 1 {
      println!("\tlast: {:?}\n", result_list.last().unwrap())
    }
  }
}


procedure main()
write(s := "knight"," --> ", s[2:0])  # drop 1st char
write(s := "sock"," --> ", s[1:-1])   # drop last
write(s := "brooms"," --> ", s[2:-1]) # drop both
end


   }. 'knight'      NB. drop first item
night
   }: 'socks'       NB. drop last item
sock
   }: }. 'brooms'   NB. drop first and last items
room


public class RM_chars {
  public static void main( String[] args ){
    System.out.println( "knight".substring( 1 ) );
    System.out.println( "socks".substring( 0, 4 ) );
    System.out.println( "brooms".substring( 1, 5 ) );
      // first, do this by selecting a specific substring
      // to exclude the first and last characters

    System.out.println( "knight".replaceAll( "^.", "" ) );
    System.out.println( "socks".replaceAll( ".$", "" ) );
    System.out.println( "brooms".replaceAll( "^.|.$", "" ) );
      // then do this using a regular expressions
  }
}


public class SubtractiveGenerator {
    public static int MAX = 1000000000;
    private int[] state;
    private int pos;

    private int mod(int n) {
        return ((n % MAX) + MAX) % MAX;
    }

    public SubtractiveGenerator(int seed) {
        state = new int[55];

        int[] temp = new int[55];
        temp[0] = mod(seed);
        temp[1] = 1;
        for(int i = 2; i < 55; ++i)
            temp[i] = mod(temp[i - 2] - temp[i - 1]);

        for(int i = 0; i < 55; ++i)
            state[i] = temp[(34 * (i + 1)) % 55];

        pos = 54;
        for(int i = 55; i < 220; ++i)
            next();
    }

    public int next() {
        int temp = mod(state[(pos + 1) % 55] - state[(pos + 32) % 55]);
        pos = (pos + 1) % 55;
        state[pos] = temp;
        return temp;
    }

    static void Main(string[] args) {
        SubtractiveGenerator gen = new SubtractiveGenerator(292929);
        for(int i = 220; i < 230; ++i)
            Console.WriteLine(i.ToString() + ": " + gen.next().ToString());
    }
}


object SuccessivePrimeDiffs {
  def main(args: Array[String]): Unit = {
    val d2 = primesByDiffs(2)(1000000)
    val d1 = primesByDiffs(1)(1000000)
    val d22 = primesByDiffs(2, 2)(1000000)
    val d24 = primesByDiffs(2, 4)(1000000)
    val d42 = primesByDiffs(4, 2)(1000000)
    val d642 = primesByDiffs(6, 4, 2)(1000000)

    if(true) println(
      s"""|Diffs: (First), (Last), Count
          |2:     (${d2.head.mkString(", ")}), (${d2.last.mkString(", ")}), ${d2.size}
          |1:     (${d1.head.mkString(", ")}), (${d1.last.mkString(", ")}), ${d1.size}
          |2-2:   (${d22.head.mkString(", ")}), (${d22.last.mkString(", ")}), ${d22.size}
          |2-4:   (${d24.head.mkString(", ")}), (${d24.last.mkString(", ")}), ${d24.size}
          |4-2:   (${d42.head.mkString(", ")}), (${d42.last.mkString(", ")}), ${d42.size}
          |6-4-2: (${d642.head.mkString(", ")}), (${d642.last.mkString(", ")}), ${d642.size}
          |""".stripMargin)
  }

  def primesByDiffs(diffs: Int*)(max: Int): LazyList[Vector[Int]] = {
    primesSliding(diffs.size + 1)
      .takeWhile(_.last <= max)
      .filter{vec => diffs.zip(vec.init).map{case (a, b) => a + b} == vec.tail}
      .to(LazyList)
  }

  def primesSliding(len: Int): Iterator[Vector[Int]] = primes.sliding(len).map(_.toVector)
  def primes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(n => !Iterator.range(3, math.sqrt(n).toInt + 1, 2).exists(n%_ == 0))
}


alert("knight".slice(1));       // strip first character
alert("socks".slice(0, -1));    // strip last character
alert("brooms".slice(1, -1));   // strip both first and last characters


"一二三四五六七八九十"[1:]' => "二三四五六七八九十"

"一二三四五六七八九十"[:-1]' => "一二三四五六七八九"

"一二三四五六七八九十"[1:-1]' => "二三四五六七八九"

"a"[1:-1] # => ""


julia> "My String"[2:end] # without first character
"y String"

julia> "My String"[1:end-1] # without last character
"My Strin"

julia> "My String"[2:end-1] # without first and last characters
"y Strin"


    s: "1234567890"
"1234567890"
    s _di 0 /Delete 1st character
"234567890"
    s _di -1+#s /Delete last character
"123456789"
    (s _di -1+#s) _di 0 /String with both 1st and last character removed
"23456789"


// written for clarity not efficiency.

#include <iostream>
using std::cout;
using std::endl;

#include <boost/array.hpp>
#include <boost/circular_buffer.hpp>

class Subtractive_generator {
private:
    static const int param_i = 55;
    static const int param_j = 24;
    static const int initial_load = 219;
    static const int mod = 1e9;
    boost::circular_buffer<int> r;
public:
    Subtractive_generator(int seed);
    int next();
    int operator()(){return next();}
};

Subtractive_generator::Subtractive_generator(int seed)
:r(param_i)
{
    boost::array<int, param_i> s;
    s[0] = seed;
    s[1] = 1;
    for(int n = 2; n < param_i; ++n){
        int t = s[n-2]-s[n-1];
        if (t < 0 ) t+= mod;
        s[n] = t;
    }

    for(int n = 0; n < param_i; ++n){
	int i = (34 * (n+1)) % param_i;
        r.push_back(s[i]);
    }
    for(int n = param_i; n <= initial_load; ++n) next();
}

int Subtractive_generator::next()
{
    int t = r[0]-r[31];
    if (t < 0) t += mod;
    r.push_back(t);
    return r[param_i-1];
}

int main()
{
    Subtractive_generator rg(292929);

    cout << "result = " << rg() << endl;
    cout << "result = " << rg() << endl;
    cout << "result = " << rg() << endl;
    cout << "result = " << rg() << endl;
    cout << "result = " << rg() << endl;
    cout << "result = " << rg() << endl;
    cout << "result = " << rg() << endl;

    return 0;
}


var limit  = 1e6
var primes = limit.primes

say "Groups of successive primes <= #{limit.commify}:"

for diffs in [[2], [1], [2,2], [2,4], [4,2], [6,4,2]] {

    var groups = []
    primes.each_cons(diffs.len+1, {|*group|
        if (group.map_cons(2, {|a,b| b-a}) == diffs) {
            groups << group
        }
    })

    say ("...for differences #{diffs}, there are #{groups.len} groups, where ",
         "the first group = #{groups.first} and the last group = #{groups.last}")
}


Imports System.Text

Module Module1

    Function Sieve(limit As Integer) As Integer()
        Dim primes As New List(Of Integer) From {2}
        Dim c(limit + 1) As Boolean REM composite = true
        REM no need to process even numbers > 2
        Dim p = 3
        While True
            Dim p2 = p * p
            If p2 > limit Then
                Exit While
            End If
            For i = p2 To limit Step 2 * p
                c(i) = True
            Next
            Do
                p += 2
            Loop While c(p)
        End While
        For i = 3 To limit Step 2
            If Not c(i) Then
                primes.Add(i)
            End If
        Next
        Return primes.ToArray
    End Function

    Function SuccessivePrimes(primes() As Integer, diffs() As Integer) As List(Of List(Of Integer))
        Dim results As New List(Of List(Of Integer))
        Dim dl = diffs.Length
        Dim i = 0
        While i < primes.Length - dl
            Dim group(dl) As Integer
            group(0) = primes(i)

            Dim j = i
            While j < i + dl
                If primes(j + 1) - primes(j) <> diffs(j - i) Then
                    GoTo outer REM continue the outermost loop
                End If
                group(j - i + 1) = primes(j + 1)

                j += 1
            End While
            results.Add(group.ToList)
outer:
            i += 1
        End While
        Return results
    End Function

    Function CollectionToString(Of T)(c As IEnumerable(Of T)) As String
        Dim builder As New StringBuilder
        builder.Append("[")

        Dim it = c.GetEnumerator()
        If it.MoveNext() Then
            builder.Append(it.Current)
        End If
        While it.MoveNext()
            builder.Append(", ")
            builder.Append(it.Current)
        End While

        builder.Append("]")
        Return builder.ToString
    End Function

    Sub Main()
        Dim primes = Sieve(999999)
        Dim diffsList = {({2}), ({1}), ({2, 2}), ({2, 4}), ({4, 2}), ({6, 4, 2})}
        Console.WriteLine("For primes less than 1,000,000:-")
        Console.WriteLine()
        For Each diffs In diffsList
            Console.WriteLine("  For differences of {0} ->", CollectionToString(diffs))
            Dim sp = SuccessivePrimes(primes, diffs)
            If sp.Count = 0 Then
                Console.WriteLine("    No groups found")
                Continue For
            End If
            Console.WriteLine("    First group   = {0}", CollectionToString(sp(0)))
            Console.WriteLine("    Last group    = {0}", CollectionToString(sp(sp.Count - 1)))
            Console.WriteLine("    Number found  = {0}", sp.Count)
            Console.WriteLine()
        Next
    End Sub

End Module


// version 1.0.6
fun main(args: Array<String>) {
    val s = "Rosetta"
    println(s.drop(1))
    println(s.dropLast(1))
    println(s.drop(1).dropLast(1))
}


{def R rosetta}                               -> rosetta

{W.rest {R}}                                  ->  osetta
{W.reverse {W.rest {W.reverse {R}}}}          -> rosett
{W.rest {W.reverse {W.rest {W.reverse {R}}}}} ->  osett

or

{W.slice 1 {W.length {R}} {R}}                ->  osetta
{W.slice 0 {- {W.length {R}} 1} {R}}          -> rosett
{W.slice 1 {- {W.length {R}} 1} {R}}          ->  osett

{def J ストリング}                              -> ストリング

{W.rest {J}}                                  ->   トリング
{W.reverse {W.rest {W.reverse {J}}}}          -> ストリン
{W.rest {W.reverse {W.rest {W.reverse {J}}}}} ->   トリン


(defn xpat2-with-seed
  "produces an xpat2 function initialized from seed"
  [seed]
  (let [e9 1000000000
        fs (fn [[i j]] [j (mod (- i j) e9)])
        s (->> [seed 1] (iterate fs) (map first) (take 55) vec)
        rinit (map #(-> % inc (* 34) (mod 55) s) (range 55))
        r-atom (atom [54 (int-array rinit)])
        update (fn [[nprev r]]
                  (let [n (-> nprev inc (mod 55))
                        rx #(get r (-> n (- %) (mod 55)))
                        rn (-> (rx 55) (- (rx 24)) (mod e9))
                        _ (aset-int r n rn)]
                    [n r]))
        xpat2 #(let [[n r] (swap! r-atom update)]
                (get r n))
        _ (dotimes [_ 165] (xpat2))]
    xpat2))

(def xpat2 (xpat2-with-seed 292929))

(println (xpat2) (xpat2) (xpat2)) ; prints: 467478574 512932792 539453717


(defun sub-rand (state)
  (let ((x (last state)) (y (last state 25)))
    ;; I take "circular buffer" very seriously (until some guru
    ;; points out it's utterly wrong thing to do)
    (setf (cdr x) state)
    (lambda () (setf x (cdr x)
		     y (cdr y)
		     (car x) (mod (- (car x) (car y)) (expt 10 9))))))

;; returns an RNG with Bentley seeding
(defun bentley-clever (seed)
  (let ((s (list 1 seed))  f)
    (dotimes (i 53)
      (push (mod (- (cadr s) (car s)) (expt 10 9)) s))
    (setf f (sub-rand
	      (loop for i from 1 to 55 collect
		    (elt s (- 54 (mod (* 34 i) 55))))))
    (dotimes (x 165) (funcall f))
    f))

;; test it (output same as everyone else's)
(let ((f (bentley-clever 292929)))
  (dotimes (x 10) (format t "~a~%" (funcall f))))


import "/math" for Int

var successivePrimes = Fn.new { |primes, diffs|
    var results = []
    var dl = diffs.count
    for (i in 0...primes.count-dl) {
        var group = List.filled(dl+1, 0)
        group[0] = primes[i]
        var outer = false
        for (j in i...i+dl) {
            var cont = false
            if (primes[j+1] - primes[j] != diffs[j-i]) {
                outer = true
                break
            }
            group[j-i+1] = primes[j+1]
        }
        if (!outer) results.add(group)
    }
    return results
}

var primes = Int.primeSieve(999999)
var diffsList = [ [2], [1], [2, 2], [2, 4], [4, 2], [6, 4, 2] ]
System.print("For primes less than 1,000,000:-\n")
for (diffs in diffsList) {
    System.print("  For differences of %(diffs) ->")
    var sp = successivePrimes.call(primes, diffs)
    var cont = false
    if (sp.count == 0) {
        System.print("    No groups found")
        cont = true
    }
    if (!cont) {
        System.print("    First group   =  %(sp[0])")
        System.print("    Last group    =  %(sp[-1])")
        System.print("    Number found  =  %(sp.count)\n")
    }
}


local(str = 'The quick grey rhino jumped over the lazy green fox.')

// String with first character removed
string_remove(#str,-startposition=1,-endposition=1)

// String with last character removed
string_remove(#str,-startposition=#str->size,-endposition=#str->size)

// String with both the first and last characters removed
string_remove(string_remove(#str,-startposition=#str->size,-endposition=#str->size),-startposition=1,-endposition=1)


string$ = "Rosetta Code"
Print Mid$(string$, 2)
Print Left$(string$, (Len(string$) - 1))
Print Mid$(string$, 2, (Len(string$) - 2))


put "pple" into x
answer char 2 to len(x) of x // pple
answer char 1 to -2 of x  // ppl
answer char 2 to -2 of x // ppl


10 a$="knight":b$="socks":c$="brooms"
20 PRINT MID$(a$,2)
30 PRINT LEFT$(b$,LEN(b$)-1)
40 PRINT MID$(c$,2,LEN(c$)-2)


import std.stdio;

struct Subtractive {
    enum MOD = 1_000_000_000;
    private int[55] state;
    private int si, sj;

    this(in int p1) pure nothrow {
        subrandSeed(p1);
    }

    void subrandSeed(int p1) pure nothrow {
        int p2 = 1;

        state[0] = p1 % MOD;
        for (int i = 1, j = 21; i < 55; i++, j += 21) {
            if (j >= 55)
                j -= 55;
            state[j] = p2;
            if ((p2 = p1 - p2) < 0)
                p2 += MOD;
            p1 = state[j];
        }

        si = 0;
        sj = 24;
        foreach (i; 0 .. 165)
            subrand();
    }

    int subrand() pure nothrow {
        if (si == sj)
            subrandSeed(0);

        if (!si--)
            si = 54;
        if (!sj--)
            sj = 54;

        int x = state[si] - state[sj];
        if (x < 0)
            x += MOD;

        return state[si] = x;
    }
}

void main() {
    auto gen = Subtractive(292_929);
    foreach (i; 0 .. 10)
        writeln(gen.subrand());
}


[*
 * (seed) lsx --
 * Seeds the subtractive generator.
 * Uses register R to hold the state.
 *]sz
[
 [* Fill ring buffer R[0] to R[54]. *]sz
 d 54:R SA              [A = R[54] = seed]sz
 1 d 33:R SB            [B = R[33] = 1]sz
 12 SC                  [C = index 12, into array R.]sz
 [55 -]SI
 [                      [Loop until C is 54:]sz
  lA lB - d lC:R         [R[C] = A - B]sz
  lB sA sB               [Parallel let A = B and B = A - B]sz
  lC 34 + d 55 !>I d sC  [C += 34 (mod 55)]sz
  54 !=L
 ]d SL x
 [* Point R[55] and R[56] into ring buffer. *]sz
 0 55:R                 [R[55] = index 0, of 55th last number.]sz
 31 56:R                [R[56] = index 31, of 24th last number.]sz
 [* Stir ring buffer. *]sz
 165 [                  [Loop 165 times:]sz
  55;R;R 56;R;R - 55;R:R [Discard a random number.]sz
  55;R 1 + d 55 !>I 55:R [R[55] += 1 (mod 55)]sz
  56;R 1 + d 55 !>I 56:R [R[56] += 1 (mod 55)]sz
  1 - d 0 <L
 ]d sL x
 LAsz LBsz LCsz LIsz LLsz
]ss

[*
 * lrx -- (random number from 0 to 10^9 - 1)
 * Returns the next number from the subtractive generator.
 * Uses register R, seeded by lsx.
 *]sz
[
 55;R;R 56;R;R -        [R[R[55]] - R[R[56]] is next random number.]sz
 d 55;R:R               [Put it in R[R[55]]. Also leave it on stack.]sz
 [55 -]SI
 55;R 1 + d 55 !>I 55:R [R[55] += 1 (mod 55)]sz
 56;R 1 + d 55 !>I 56:R [R[56] += 1 (mod 55)]sz
 [1000000000 +]sI
 1000000000 % d 0 >I    [Random number = it (mod 10^9)]sz
 LIsz
]sr

[* Seed with 292929 and print first three random numbers. *]sz
292929 lsx
lrx psz
lrx psz
lrx psz


const PRIME_LIMIT=1_000_000;
var [const] BI=Import("zklBigNum");  // libGMP
var [const] primeBitMap=Data(PRIME_LIMIT).fill(0x30);   // one big string
p:= BI(1);
while(p.nextPrime()<=PRIME_LIMIT){ primeBitMap[p]="1" } // bitmap of primes

fcn primeWindows(m,deltas){ // eg (6,4,2)
   n,r := 0,List();
   ds:=deltas.len().pump(List,'wrap(n){ deltas[0,n+1].sum(0) });  // (6,10,12)
   sp:=Data(Void,"1" + "0"*deltas.sum(0));
   foreach n in (ds){ sp[n]="1" } // "1000001000101"
   while(n=primeBitMap.find(sp,n+1)){ r.append(n) }  //  (31, 61, 271,...)
   r.apply('wrap(n){ T(n).extend(ds.apply('+(n))) }) //( (31,37,41,43), (61,67,71,73), (271,277,281,283) ...)
}


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


:- object(top_and_tail).

    :- public(test/1).
    test(String) :-
        sub_atom(String, 1, _, 0, MinusTop),
        write('String with first character cut: '), write(MinusTop), nl,
        sub_atom(String, 0, _, 1, MinusTail),
        write('String with last character cut: '), write(MinusTail), nl,
        sub_atom(String, 1, _, 1, MinusTopAndTail),
        write('String with first and last characters cut: '), write(MinusTopAndTail), nl.

:- end_object.