BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the   #
      # subsequent members are the lowest number coprime to the previous one  #
      # and not coprime to the one before that, that haven't appeared in the  #
      # sequence yet                                                          #
    # iterative Greatest Common Divisor routine, returns the gcd of m and n   #
    PROC gcd = ( INT m, n )INT:
         BEGIN
            INT a := ABS m, b := ABS n;
            WHILE b /= 0 DO
                INT new a = b;
                b        := a MOD b;
                a        := new a
            OD;
            a
         END # gcd # ;
    # returns an array of the Yellowstone seuence up to n                     #
    OP   YELLOWSTONE = ( INT n )[]INT:
         BEGIN
            [ 1 : n ]INT result;
            IF n > 0 THEN
                result[ 1 ] := 1;
                IF n > 1 THEN
                    result[ 2 ] := 2;
                    IF n > 2 THEN
                        result[ 3 ] := 3;
                        # guess the maximum element will be n, if it is larger, used will be enlarged #
                        REF[]BOOL used := HEAP[ 1 : n ]BOOL;
                        used[ 1 ] := used[ 2 ] := used[ 3 ] := TRUE;
                        FOR i FROM 4 TO UPB used DO used[ i ] := FALSE OD;
                        FOR i FROM 4 TO UPB result DO
                            INT p1      = result[ i - 1 ];
                            INT p2      = result[ i - 2 ];
                            BOOL found := FALSE;
                            FOR j WHILE NOT found DO
                                IF j > UPB used THEN
                                    # not enough elements in used - enlarge it #
                                    REF[]BOOL new used := HEAP[ 1 : 2 * UPB used ]BOOL;
                                    new used[ 1 : UPB used ] := used;
                                    FOR k FROM UPB used + 1 TO UPB new used DO new used[ k ] := FALSE OD;
                                    used := new used
                                FI;
                                IF NOT used[ j ] THEN
                                    IF found := gcd( j, p1 ) = 1 AND gcd( j, p2 ) /= 1
                                    THEN
                                        result[ i ] := j;
                                        used[   j ] := TRUE
                                    FI
                                FI
                            OD
                        OD
                    FI
                FI
            FI;
            result
         END # YELLOWSTONE # ;
    []INT ys = YELLOWSTONE 30;
    FOR i TO UPB ys DO
        print( ( " ", whole( ys[ i ], 0 ) ) )
    OD
END


Start,Programs,Applications,Mozilla Firefox,Inputbox:address bar>www.yahoo.co.uk,
Button:Go,Area:browser window,Inputbox:searchbox>elephants,Button:Search


import Network.HTTP
import Text.Parsec

data YahooSearchItem = YahooSearchItem {
    itemUrl, itemTitle, itemContent :: String }

data YahooSearch = YahooSearch {
    searchQuery :: String,
    searchPage :: Int,
    searchItems :: [YahooSearchItem] }

-- URL for Yahoo! searches, without giving a page number
yahooUrl = "http://search.yahoo.com/search?p="

-- make an HTTP request and return a YahooSearch
yahoo :: String -> IO YahooSearch
yahoo q = simpleHTTP (getRequest $ yahooUrl ++ q) >>=
    getResponseBody >>= return . YahooSearch q 1 . items

-- get some results and return the next page of results
next :: YahooSearch -> IO YahooSearch
next (YahooSearch q p _) =
    simpleHTTP (getRequest $
    -- add the page number to the search
    yahooUrl ++ q ++ "&b=" ++ show (p + 1)) >>=
    getResponseBody >>= return . YahooSearch q (p + 1) . items

printResults :: YahooSearch -> IO ()
printResults (YahooSearch q p items) = do
    putStrLn $ "Showing Yahoo! search results for query: " ++ q
    putStrLn $ "Page: " ++ show p
    putChar '\n'
    mapM_ printOne items
    where
        printOne (YahooSearchItem itemUrl itemTitle itemContent) = do
            putStrLn $ "URL   : " ++ itemUrl
            putStrLn $ "Title : " ++ itemTitle
            putStrLn $ "Abstr : " ++ itemContent
            putChar '\n'

urlTag, titleTag, contentTag1, contentTag2, ignoreTag,
    ignoreText :: Parsec String () String

-- parse a tag containing the URL of a search result
urlTag = do { string "<a id=\"link-";
    many digit; string "\" class=\"yschttl spt\" href=\"";
    url <- manyTill anyChar (char '"'); manyTill anyChar (char '>');
    return url }

-- the title comes after the URL tag, so parse it first, discard it
-- and get the title text
titleTag = do { urlTag; manyTill anyChar (try (string "")) }

-- parse a tag containing the description of the search result
-- the tag can be named "sm-abs" or "abstr"
contentTag1 = do { string "
";
    manyTill anyChar (try (string "
")) }

contentTag2 = do { string "
";
    manyTill anyChar (try (string "
")) }

-- parse a tag and discard it
ignoreTag = do { char ('<'); manyTill anyChar (char '>');
    return "" }

-- parse some text and discard it
ignoreText = do { many1 (noneOf "<"); return "" }

-- return only non-empty strings
nonempty :: [String] -> Parsec String () [String]
nonempty xs = return [ x | x <- xs, not (null x) ]

-- a template to parse a whole source file looking for items of the
-- same class
parseCategory x = do
    res <- many x
    eof
    nonempty res

urls, titles, contents :: Parsec String () [String]

-- parse HTML source looking for URL tags of the search results
urls = parseCategory url where
    url = (try urlTag) <|> ignoreTag <|> ignoreText

-- parse HTML source looking for titles of the search results
titles = parseCategory title where
    title = (try titleTag) <|> ignoreTag <|> ignoreText

-- parse HTML source looking for descriptions of the search results
contents = parseCategory content where
    content = (try contentTag1) <|> (try contentTag2) <|>
        ignoreTag <|> ignoreText

-- parse the HTML source three times looking for URL, title and
-- description of all search results and return them as a list of
-- YahooSearchItem
items :: String -> [YahooSearchItem]
items q =
    let ignoreOrKeep = either (const []) id
        us = ignoreOrKeep $ parse urls "" q
        ts = ignoreOrKeep $ parse titles "" q
        cs = ignoreOrKeep $ parse contents "" q
    in [ YahooSearchItem { itemUrl = u, itemTitle = t, itemContent = c } |
        (u, t, c) <- zip3 us ts cs ]


zigzag1:=proc(n)
  uses ArrayTools;
  local i,u,v,a;
  u:=Replicate(<-1,1>,n):
  v:=Vector[row](1..n,i->i*(2*i-3)):
  v:=Reshape(<v+~1,v+~2>,2*n):
  a:=Matrix(n,n):
  for i to n do
    a[...,i]:=v[i+1..i+n];
    v+=u
  od:
  a
end:

zigzag2:=proc(n)
  local i,v,a;
  a:=zigzag1(n);
  v:=Vector(1..n-1,i->i^2);
  for i from 2 to n do
    a[n+2-i..n,i]-=v[1..i-1]
  od;
  a
end:


def (doors n)
  let door (table)
    for step 1 (step <= n) ++step
      for j 0 (j < n) (j <- j+step)
        zap! not door.j

    for j 0 (j < n) ++j
      when door.j
        pr j
        pr " "


yellowstone: function [n][
    result: new [1 2 3]
    present: new [1 2 3]
    start: new 4
    while [n > size result][
        candidate: new start
        while ø [
            if all? @[
                not? contains? present candidate
                1 = gcd @[candidate last result]
                1 <> gcd @[candidate get result (size result)-2]
            ][
                'result ++ candidate
                'present ++ candidate
                while [contains? present start] -> inc 'start
                break
            ]
            inc 'candidate
        ]
    ]
    return result
]

print yellowstone 30


A := [], in_seq := []
loop 30 {
    n := A_Index
    if n <=3
        A[n] := n,    in_seq[n] := true
    else while true
    {
        s := A_Index
        if !in_seq[s] && relatively_prime(s, A[n-1]) && !relatively_prime(s, A[n-2])
        {
            A[n] := s
            in_seq[s] := true
            break
        }
    }
}
for i, v in A
    result .= v ","
MsgBox % result := "[" Trim(result, ",") "]"
return
;--------------------------------------
relatively_prime(a, b){
    return (GCD(a, b) = 1)
}
;--------------------------------------
GCD(a, b) {
    while b
        b := Mod(a | 0x0, a := b)
    return a
}


link printf,strings

procedure main()
YS := YahooSearch("rosettacode")
every 1 to 2 do {   # 2 pages
   YS.readnext()
   YS.showinfo()
   }
end

class YahooSearch(urlpat,page,response)  #: class for Yahoo Search

   method readnext()    #: read the next page of search results
      self.page +:= 1   # can't find as w|w/o self
      readurl()
   end

   method readurl()     #: read the url
      url := sprintf(self.urlpat,(self.page-1)*10+1)
      m := open(url,"m")  | stop("Unable to open : ",url)
      every (self.response := "") ||:= |read(m)
      close(m)
      self.response := deletec(self.response,"\x00") # kill stray NULs
   end

   method showinfo()    #: show the info of interest
      self.response ? repeat {
         (tab(find("<")) & ="")+1)
         title := tab(find("<")) & ="

"
         tab(find("<")) & =("
" | "
")
         abstr := tab(find("<")) & ="
"

         printf("\nTitle : %i\n",title)
         printf("URL   : %i\n",url)
         printf("Abstr : %i\n",abstr)
         }
   end

initially(searchtext)    #: initialize each instance
   urlpat := sprintf("http://search.yahoo.com/search?p=%s&b=%%d",searchtext)
   page := 0
end


ZigZag[size_Integer/;size>0]:=Module[{empty=ConstantArray[0,{size,size}]},
 empty=ReplacePart[empty,{i_,j_}:>1/2 (i+j)^2-(i+j)/2-i (1-Mod[i+j,2])-j Mod[i+j,2]];
 ReplacePart[empty,{i_,j_}/;i+j>size+1:> size^2-tmp[[size-i+1,size-j+1]]-1]
]


function matrix = zigZag(n)

    %This is very unintiutive. This algorithm parameterizes the
    %zig-zagging movement along the matrix indicies. The easiest way to see
    %what this algorithm does is to go through line-by-line and write out
    %what the algorithm does on a peace of paper.

    matrix = zeros(n);
    counter = 1;
    flipCol = true;
    flipRow = false;

    %This for loop does the top-diagonal of the matrix
    for i = (2:n)
        row = (1:i);
        column = (1:i);

        %Causes the zig-zagging. Without these conditionals,
        %you would end up with a diagonal matrix.
        %To see what happens, comment these conditionals out.
        if flipCol
            column = fliplr(column);
            flipRow = true;
            flipCol = false;
        elseif flipRow
            row = fliplr(row);
            flipRow = false;
            flipCol = true;
        end

        %Selects a diagonal of the zig-zag matrix and places the
        %correct integer value in each index along that diagonal
        for j = (1:numel(row))
            matrix(row(j),column(j)) = counter;
            counter = counter + 1;
        end
    end

    %This for loop does the bottom-diagonal of the matrix
    for i = (2:n)
        row = (i:n);
        column = (i:n);

        %Causes the zig-zagging. Without these conditionals,
        %you would end up with a diagonal matrix.
        %To see what happens comment these conditionals out.
        if flipCol
            column = fliplr(column);
            flipRow = true;
            flipCol = false;
        elseif flipRow
            row = fliplr(row);
            flipRow = false;
            flipCol = true;
        end

        %Selects a diagonal of the zig-zag matrix and places the
        %correct integer value in each index along that diagonal
        for j = (1:numel(row))
            matrix(row(j),column(j)) = counter;
            counter = counter + 1;
        end
    end

end


let a => import 'arrays';
let s => import 'stream';
let io => import 'io';

let toggle doors m =>
	a.stream doors
	-> s.enumerate
	-> s.map (@ s n => [+ (a.at n 0) 1; a.at n 1])
	-> s.map (@ s n => switch n {
			(@ s n => == (% (a.at n 0) m) 0) => ! (a.at n 1);
			true => a.at n 1;
		})
	-> s.collect
	;

s.range 100
-> s.map false
-> s.collect : doors
-> s.range 1 100
-> s.reduce doors toggle
-> a.stream
-> s.map (@ s n => switch 0 {
		n => 'Open';
		true => 'Closed';
	} -- io.writeln io.stdout)
-> s.drain
;


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

typedef struct lnode_t {
    struct lnode_t *prev;
    struct lnode_t *next;
    int v;
} Lnode;

Lnode *make_list_node(int v) {
    Lnode *node = malloc(sizeof(Lnode));
    if (node == NULL) {
        return NULL;
    }
    node->v = v;
    node->prev = NULL;
    node->next = NULL;
    return node;
}

void free_lnode(Lnode *node) {
    if (node == NULL) {
        return;
    }

    node->v = 0;
    node->prev = NULL;
    free_lnode(node->next);
    node->next = NULL;
}

typedef struct list_t {
    Lnode *front;
    Lnode *back;
    size_t len;
} List;

List *make_list() {
    List *list = malloc(sizeof(List));
    if (list == NULL) {
        return NULL;
    }
    list->front = NULL;
    list->back = NULL;
    list->len = 0;
    return list;
}

void free_list(List *list) {
    if (list == NULL) {
        return;
    }
    list->len = 0;
    list->back = NULL;
    free_lnode(list->front);
    list->front = NULL;
}

void list_insert(List *list, int v) {
    Lnode *node;

    if (list == NULL) {
        return;
    }

    node = make_list_node(v);
    if (list->front == NULL) {
        list->front = node;
        list->back = node;
        list->len = 1;
    } else {
        node->prev = list->back;
        list->back->next = node;
        list->back = node;
        list->len++;
    }
}

void list_print(List *list) {
    Lnode *it;

    if (list == NULL) {
        return;
    }

    for (it = list->front; it != NULL; it = it->next) {
        printf("%d ", it->v);
    }
}

int list_get(List *list, int idx) {
    Lnode *it = NULL;

    if (list != NULL && list->front != NULL) {
        int i;
        if (idx < 0) {
            it = list->back;
            i = -1;
            while (it != NULL && i > idx) {
                it = it->prev;
                i--;
            }
        } else {
            it = list->front;
            i = 0;
            while (it != NULL && i < idx) {
                it = it->next;
                i++;
            }
        }
    }

    if (it == NULL) {
        return INT_MIN;
    }
    return it->v;
}

///////////////////////////////////////

typedef struct mnode_t {
    int k;
    bool v;
    struct mnode_t *next;
} Mnode;

Mnode *make_map_node(int k, bool v) {
    Mnode *node = malloc(sizeof(Mnode));
    if (node == NULL) {
        return node;
    }
    node->k = k;
    node->v = v;
    node->next = NULL;
    return node;
}

void free_mnode(Mnode *node) {
    if (node == NULL) {
        return;
    }
    node->k = 0;
    node->v = false;
    free_mnode(node->next);
    node->next = NULL;
}

typedef struct map_t {
    Mnode *front;
} Map;

Map *make_map() {
    Map *map = malloc(sizeof(Map));
    if (map == NULL) {
        return NULL;
    }
    map->front = NULL;
    return map;
}

void free_map(Map *map) {
    if (map == NULL) {
        return;
    }
    free_mnode(map->front);
    map->front = NULL;
}

void map_insert(Map *map, int k, bool v) {
    if (map == NULL) {
        return;
    }
    if (map->front == NULL) {
        map->front = make_map_node(k, v);
    } else {
        Mnode *it = map->front;
        while (it->next != NULL) {
            it = it->next;
        }
        it->next = make_map_node(k, v);
    }
}

bool map_get(Map *map, int k) {
    if (map != NULL) {
        Mnode *it = map->front;
        while (it != NULL && it->k != k) {
            it = it->next;
        }
        if (it != NULL) {
            return it->v;
        }
    }
    return false;
}

///////////////////////////////////////

int gcd(int u, int v) {
    if (u < 0) u = -u;
    if (v < 0) v = -v;
    if (v) {
        while ((u %= v) && (v %= u));
    }
    return u + v;
}

List *yellow(size_t n) {
    List *a;
    Map *b;
    int i;

    a = make_list();
    list_insert(a, 1);
    list_insert(a, 2);
    list_insert(a, 3);

    b = make_map();
    map_insert(b, 1, true);
    map_insert(b, 2, true);
    map_insert(b, 3, true);

    i = 4;

    while (n > a->len) {
        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {
            list_insert(a, i);
            map_insert(b, i, true);
            i = 4;
        }
        i++;
    }

    free_map(b);
    return a;
}

int main() {
    List *a = yellow(30);
    list_print(a);
    free_list(a);
    putc('\n', stdout);
    return 0;
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class YahooSearch {
    private String query;
    // Page number
    private int page = 1;
    // Regexp to look for the individual results in the returned page
    private static final Pattern pattern = Pattern.compile(
        "(.+?)
.*?
(.+?)
");

    public YahooSearch(String query) {
        this.query = query;
    }

    public List<YahooResult> search() throws MalformedURLException, URISyntaxException, IOException {
        // Build the search string, starting with the Yahoo search URL,
        // then appending the query and optionally the page number (if > 1)
        StringBuilder searchUrl = new StringBuilder("http://search.yahoo.com/search?");
        searchUrl.append("p=").append(URLEncoder.encode(query, "UTF-8"));
        if (page > 1) {searchUrl.append("&b=").append((page - 1) * 10 + 1);}
        // Query the Yahoo search engine
        URL url = new URL(searchUrl.toString());
        List<YahooResult> result = new ArrayList<YahooResult>();
        StringBuilder sb = new StringBuilder();
        // Get the search results using a buffered reader
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            // Read the results line by line
            String line = in.readLine();
            while (line != null) {
                sb.append(line);
                line = in.readLine();
            }
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
        finally {
            try {in.close();} catch (Exception ignoreMe) {}
        }
        String searchResult = sb.toString();
        // Look for the individual results by matching the regexp pattern
        Matcher matcher = pattern.matcher(searchResult);
        while (matcher.find()) {
            // Extract the result URL, title and excerpt
            String resultUrl = URLDecoder.decode(matcher.group(1), "UTF-8");
            String resultTitle = matcher.group(2).replaceAll("</?b>", "").replaceAll("<wbr ?/?>", "");
            String resultContent = matcher.group(3).replaceAll("</?b>", "").replaceAll("<wbr ?/?>", "");
            // Create a new YahooResult and add to the list
            result.add(new YahooResult(resultUrl, resultTitle, resultContent));
        }
        return result;
    }

    public List<YahooResult> search(int page) throws MalformedURLException, URISyntaxException, IOException {
        // Set the page number and search
        this.page = page;
        return search();
    }

    public List<YahooResult> nextPage() throws MalformedURLException, URISyntaxException, IOException {
        // Increment the page number and search
        page++;
        return search();
    }

    public List<YahooResult> previousPage() throws MalformedURLException, URISyntaxException, IOException {
        // Decrement the page number and search; if the page number is 1 return an empty list
        if (page > 1) {
            page--;
            return search();
        } else return new ArrayList<YahooResult>();
    }
}

class YahooResult {
    private URL url;
    private String title;
    private String content;

    public URL getUrl() {
        return url;
    }

    public void setUrl(URL url) {
        this.url = url;
    }

    public void setUrl(String url) throws MalformedURLException {
        this.url = new URL(url);
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public YahooResult(URL url, String title, String content) {
        setUrl(url);
        setTitle(title);
        setContent(content);
    }

    public YahooResult(String url, String title, String content) throws MalformedURLException {
        setUrl(url);
        setTitle(title);
        setContent(content);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (title != null) {
            sb.append(",title=").append(title);
        }
        if (url != null) {
            sb.append(",url=").append(url);
        }
        return sb.charAt(0) == ',' ? sb.substring(1) : sb.toString();
    }
}

public class TestYahooSearch {
    public static void main(String[] args) throws MalformedURLException, URISyntaxException, IOException {
        // Create a new search
        YahooSearch search = new YahooSearch("Rosetta code");
        // Get the search results
        List<YahooResult> results = search.search();
        // Show the search results
        for (YahooResult result : results) {
            System.out.println(result.toString());
        }
    }
}


%Zigzag Matrix. Nigel Galloway, February 3rd., 2020
int: Size;
array [1..Size,1..Size] of var 1..Size*Size: zigzag;
constraint zigzag[1,1]=1 /\ zigzag[Size,Size]=Size*Size;
constraint forall(n in {2*g | g in 1..Size div 2})(zigzag[1,n]=zigzag[1,n-1]+1 /\ forall(g in 2..n)(zigzag[g,n-g+1]=zigzag[g-1,n-g+2]+1));
constraint forall(n in {2*g + ((Size-1) mod 2) | g in 1..(Size-1) div 2})(zigzag[n,Size]=zigzag[n-1,Size]+1 /\ forall(g in 1..Size-n)(zigzag[n+g,Size-g]=zigzag[n+g-1,Size-g+1]+1));
constraint forall(n in {2*g+1 | g in 1..(Size-1) div 2})(zigzag[n,1]=zigzag[n-1,1]+1 /\ forall(g in 2..n)(zigzag[n-g+1,g]=zigzag[n-g+2,g-1]+1));
constraint forall(n in {2*g+((Size) mod 2) | g in 1..(Size-1) div 2})(zigzag[Size,n]=zigzag[Size,n-1]+1 /\ forall(g in 1..Size-n)(zigzag[Size-g,n+g]=zigzag[Size-g+1,n+g-1]+1));
output [show2d(zigzag)];


; unoptimized
+^[
  @var doors []

  @for i rangei [1 100]
    @for j rangei [i 100 i]
      :[email protected] `j doors

  @for i rangei [1 100]
    @if `i doors
      !console.log "door {i} is open"
]
; optimized, map square over 1 to 10
!*^@sq @to 10


#include <iostream>
#include <numeric>
#include <set>

template <typename integer>
class yellowstone_generator {
public:
    integer next() {
        n2_ = n1_;
        n1_ = n_;
        if (n_ < 3) {
            ++n_;
        } else {
            for (n_ = min_; !(sequence_.count(n_) == 0
                && std::gcd(n1_, n_) == 1
                && std::gcd(n2_, n_) > 1); ++n_) {}
        }
        sequence_.insert(n_);
        for (;;) {
            auto it = sequence_.find(min_);
            if (it == sequence_.end())
                break;
            sequence_.erase(it);
            ++min_;
        }
        return n_;
    }
private:
    std::set<integer> sequence_;
    integer min_ = 1;
    integer n_ = 0;
    integer n1_ = 0;
    integer n2_ = 0;
};

int main() {
    std::cout << "First 30 Yellowstone numbers:\n";
    yellowstone_generator<unsigned int> ygen;
    std::cout << ygen.next();
    for (int i = 1; i < 30; ++i)
        std::cout << ' ' << ygen.next();
    std::cout << '\n';
    return 0;
}


import std.numeric;
import std.range;
import std.stdio;

class Yellowstone {
    private bool[int] sequence_;
    private int min_ = 1;
    private int n_ = 0;
    private int n1_ = 0;
    private int n2_ = 0;

    public this() {
        popFront();
    }

    public bool empty() {
        return false;
    }

    public int front() {
        return n_;
    }

    public void popFront() {
        n2_ = n1_;
        n1_ = n_;
        if (n_ < 3) {
            ++n_;
        } else {
            for (n_ = min_;
                !(n_ !in sequence_ && gcd(n1_, n_) == 1 && gcd(n2_, n_) > 1);
                ++n_) {
                // empty
            }
        }
        sequence_[n_] = true;
        while (true) {
            if (min_ !in sequence_) {
                break;
            }
            sequence_.remove(min_);
            ++min_;
        }
    }
}

void main() {
    new Yellowstone().take(30).writeln();
}


""" Rosetta Code Yahoo search task. https://rosettacode.org/wiki/Yahoo!_search_interface """

using EzXML
using HTTP
using Logging

const pagesize = 7
const URI = "https://search.yahoo.com/search?fr=opensearch&pz=$pagesize&"

struct SearchResults
    title::String
    content::String
    url::String
end

mutable struct YahooSearch
    search::String
    yahoourl::String
    currentpage::Int
    usedpages::Vector{Int}
    results::Vector{SearchResults}
end
YahooSearch(s, url = URI) = YahooSearch(s, url, 1, Int[], SearchResults[])

function NextPage(yah::YahooSearch, link, pagenum)
    oldpage = yah.currentpage
    yah.currentpage = pagenum
    search(yah)
    yah.currentpage = oldpage
end

function search(yah::YahooSearch)
    push!(yah.usedpages, yah.currentpage)
    queryurl = yah.yahoourl * "b=$(yah.currentpage)&p=" * HTTP.escapeuri(yah.search)
    req = HTTP.request("GET", queryurl)
    # Yahoo's HTML is nonstandard, so send excess warnings from the parser to NullLogger
    html = with_logger(NullLogger()) do
        parsehtml(String(req.body))
    end
    for div in findall("//li/div", html)
        if haskey(div, "class")
            if startswith(div["class"], "dd algo") &&
               (a = findfirst("div/h3/a", div)) != nothing &&
               haskey(a, "href")
                url, title, content = a["href"], nodecontent(a), "None"
                for span in findall("div/p/span", div)
                    if haskey(span, "class") && occursin("fc-falcon", span["class"])
                        content = nodecontent(span)
                    end
                end
                push!(yah.results, SearchResults(title, content, url))
            elseif startswith(div["class"], "dd pagination")
                for a in findall("div/div/a", div)
                    if haskey(a, "href")
                        lnk, n = a["href"], tryparse(Int, nodecontent(a))
                        !isnothing(n) && !(n in yah.usedpages) && NextPage(yah, lnk, n)
                    end
                end
            end
        end
    end
end

ysearch = YahooSearch("RosettaCode")
search(ysearch)
println("Searching Yahoo for `RosettaCode`:")
println(
    "Found ",
    length(ysearch.results),
    " entries on ",
    length(ysearch.usedpages),
    " pages.\n",
)
for res in ysearch.results
    println("Title: ", res.title)
    println("Content: ", res.content)
    println("URL:     ", res.url, "\n")
end


// version 1.2.0

import java.net.URL

val rx = Regex("""
.+?(.*?).+?class="abstract ellipsis">(.*?)
""")

class YahooResult(var title: String, var link: String, var text: String) {

    override fun toString() = "\nTitle: $title\nLink : $link\nText : $text"
}

class YahooSearch(val query: String, val page: Int = 0) {

    private val content: String

    init {
        val yahoo = "http://search.yahoo.com/search?"
        val url = URL("${yahoo}p=$query&b=${page * 10 + 1}")
        content = url.readText()
    }

    val results: MutableList<YahooResult>
        get() {
            val list = mutableListOf<YahooResult>()
            for (mr in rx.findAll(content)) {
               val title = mr.groups[2]!!.value.replace("", "").replace("", "")
               val link  = mr.groups[1]!!.value
               val text  = mr.groups[3]!!.value.replace("", "").replace("", "")
               list.add (YahooResult(title, link, text))
            }
            return list
        }

    fun nextPage() = YahooSearch(query, page + 1)

    fun getPage(newPage: Int) = YahooSearch(query, newPage)
}

fun main(args: Array<String>) {
    for (page in 0..1) {
        val x = YahooSearch("rosettacode", page)
        println("\nPAGE ${page + 1} =>")
        for (result in x.results.take(3)) println(result)
    }
}


MODULE ZigZag EXPORTS Main;

IMPORT IO, Fmt;

TYPE Matrix = REF ARRAY OF ARRAY OF CARDINAL;

PROCEDURE Create(size: CARDINAL): Matrix =
  PROCEDURE move(VAR i, j: INTEGER) =
    BEGIN
      IF j < (size - 1) THEN
        IF (i - 1) < 0 THEN
          i := 0;
        ELSE
          i := i - 1;
        END;
        INC(j);
      ELSE
        INC(i);
      END;
    END move;

  VAR data := NEW(Matrix, size, size);
      x, y: INTEGER := 0;
  BEGIN
    FOR v := 0 TO size * size - 1 DO
      data[y, x] := v;
      IF (x + y) MOD 2 = 0 THEN
        move(y, x);
      ELSE
        move(x, y);
      END;
    END;
    RETURN data;
  END Create;

PROCEDURE Print(data: Matrix) =
  BEGIN
    FOR i := FIRST(data^) TO LAST(data^) DO
      FOR j := FIRST(data[0]) TO LAST(data[0]) DO
        IO.Put(Fmt.F("%3s", Fmt.Int(data[i, j])));
      END;
      IO.Put("\n");
    END;
  END Print;

BEGIN
  Print(Create(5));
END ZigZag.


MOD Doors;

IMP Agg.Table;
IMP Std.String;
IMP IO.Terminal USE Out;

VAR door <- {}; EVERY door[1:to(100), "closed"];

DEF toggle(num) door[num] <- door[num] = "open" => "closed" // "open";

EVERY WITH pass <- 1:to(100), num <- pass:to(100, pass) DO toggle(num);

Out:write('Doors {door @ String.T}.');

END Doors.


program Yellowstone_sequence;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  Boost.Generics.Collection,
  Boost.Process;

function gdc(x, y: Integer): Integer;
begin
  while y <> 0 do
  begin
    var tmp := x;
    x := y;
    y := tmp mod y;
  end;
  Result := x;
end;

function Yellowstone(n: Integer): TArray<Integer>;
var
  m: TDictionary<Integer, Boolean>;
  a: TArray<Integer>;
begin
  m.Init;
  SetLength(a, n + 1);
  for var i := 1 to 3 do
  begin
    a[i] := i;
    m[i] := True;
  end;

  var min := 4;

  for var c := 4 to n do
  begin
    var i := min;
    repeat
      if not m[i, false] and (gdc(a[c - 1], i) = 1) and (gdc(a[c - 2], i) > 1) then
      begin
        a[c] := i;
        m[i] := true;
        if i = min then
          inc(min);
        Break;
      end;
      inc(i);
    until false;
  end;

  Result := copy(a, 1, length(a));
end;

begin
  var x: TArray<Integer>;
  SetLength(x, 100);
  for var i in Range(100) do
    x[i] := i + 1;

  var y := yellowstone(High(x));

  writeln('The first 30 Yellowstone numbers are:');
  for var i := 0 to 29 do
    Write(y[i], ' ');
  Writeln;

  //Plotting

  var plot := TPipe.Create('gnuplot -p', True);
  plot.WritelnA('unset key; plot ''-''');

  for var i := 0 to High(x) do
    plot.WriteA('%d %d'#10, [x[i], y[i]]);
  plot.WritelnA('e');

  writeln('Press enter to close');
  Readln;
  plot.Kill;
  plot.Free;
end.


Manipulate[
 Column[Flatten[
   StringCases[
    StringCases[
     URLFetch[
      "http://search.yahoo.com/search?p=" <> query <> "&b=" <>
       [email protected]], "<ol" ~~ ___ ~~ "
"],
    "" ~~
      Shortest[title__] ~~
      "
" | "
" ~~
      Shortest[abstr__] ~~ "
" :>
     Column[{Hyperlink[Style[#[[1]], Larger], #[[2]]], #[[3]],
         Style[#[[2]], Smaller]} &@
       StringReplace[{title, url,
         abstr}, {"<" ~~ Shortest[__] ~~ ">" -> "",
         "&#" ~~ n : DigitCharacter ... ~~ ";" :>
          FromCharacterCode[[email protected]], "&" -> "&",
         """ -> "\"", "<" -> "<", ">" -> ">"}]]], 1],
  Spacings -> 2], {{input, "", "Yahoo!"},
  InputField[[email protected], String] &}, {{query, ""},
  ControlType -> None}, {{page, 1}, ControlType -> None},
 Row[{Button["Search", page = 1; query = input],
   Button["Prev", page -= 10, Enabled -> Dynamic[page >= 10]],
   Button["Next", page += 10]}]]


import httpclient, strutils, htmlparser, xmltree, strtabs
const
  PageSize = 7
  YahooURLPattern = "https://search.yahoo.com/search?fr=opensearch&b=$$#&pz=$#&p=".format(PageSize)
type
  SearchResult = ref object
    url, title, content: string
  SearchInterface = ref object
    client: HttpClient
    urlPattern: string
    page: int
    results: array[PageSize+2, SearchResult]
proc newSearchInterface(question: string): SearchInterface =
  new result
  result.client = newHttpClient()
#  result.client = newHttpClient(proxy = newProxy(
#      "http://localhost:40001")) # only http_proxy supported
  result.urlPattern = YahooURLPattern&question
proc search(si: SearchInterface) =
  let html = parseHtml(si.client.getContent(si.urlPattern.format(
      si.page*PageSize+1)))
  var
    i: int
    attrs: XmlAttributes
  for d in html.findAll("div"):
    attrs = d.attrs
    if attrs != nil and attrs.getOrDefault("class").startsWith("dd algo algo-sr relsrch"):
      let d_inner = d.child("div")
      for a in d_inner.findAll("a"):
        attrs = a.attrs
        if attrs != nil and attrs.getOrDefault("class") == " ac-algo fz-l ac-21th lh-24":
          si.results[i] = SearchResult(url: attrs["href"], title: a.innerText,
              content: d.findAll("p")[0].innerText)
          i+=1
          break
  while i < len(si.results) and si.results[i] != nil:
    si.results[i] = nil
    i+=1
proc nextPage(si: SearchInterface) =
  si.page+=1
  si.search()

proc echoResult(si: SearchInterface) =
  for res in si.results:
    if res == nil:
      break
    echo(res[])

var searchInf = newSearchInterface("weather")
searchInf.search()
searchInf.echoResult()
echo("searching for next page...")
searchInf.nextPage()
searchInf.echoResult()


declare
  [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']}
  [StringX] = {Module.link ['x-oz://system/String.ozf']}
  [Regex] = {Module.link ['x-oz://contrib/regex']}

  %% Displays page 1 and 3 of the search results.
  %% The user can request and display more with context menu->Actions->Make Needed.
  proc {ExampleUsage}
     Pages = {YahooSearch "Rosetta code"}
  in
     {Inspector.configure widgetShowStrings true}
     {ForAll {Nth Pages 1} Value.makeNeeded}
     {ForAll {Nth Pages 3} Value.makeNeeded}
     %% Display the infinite list of search result pages.
     {Inspect Pages}
  end

  %% Returns a lazy list of pages.
  %% A page is a lazy list of entries like this: result(url:U title:T content:C).
  fun {YahooSearch Query}
     FetchURL = {CreateURLFetcher}

     fun {Page Nr}
	StartResult = (Nr-1)*10+1
	%% only retrieve it when really needed
	Doc = {Value.byNeed fun {$}
			       {FetchURL "http://search.yahoo.com/search"
				["p"#Query "b"#{Int.toString StartResult}]}
			    end}
	RE = "<a class=\"yschttl spt\" href="
     in
	%% Lazily returns results.
	%% In this way it is possible to build the pages list structure
	%% without creating the single elements
	%% (e.g. retrieve page 1 and 3 but not 2).
	for Match in {Regex.allMatches RE Doc} yield:Yield do
	   Xs = {List.drop Doc Match.0.2}
	in
	   {Yield {ParseEntry Xs}}
	end
     end
  in
     for PageNr in 1;PageNr+1 yield:Yield do
	{Yield {Page PageNr}}
     end
  end

  fun {CreateURLFetcher}
     Client = {New HTTPClient.cgiGET
	       init(inPrms(toFile:false toStrm:true)
		    httpReqPrms
		   )}
     %% close when no longer used
     {Finalize.register Client proc {$ C} {C closeAll(true)} end}

     fun {FetchURL Url Params}
	OutParams
     in
	{Client getService(Url Params ?OutParams ?_)}
	OutParams.sOut
     end
  in
     FetchURL
  end

  %% Xs: String containing HtmL
  %% Result: "result(url:U title:T content:C)" or "parseError"
  fun {ParseEntry Xs}
     proc {Parse Root}
	R1 R2 R3 R4 R4 R5 R6 R7
	Url = {Fix {QuotedString Xs R1}}
	{Const ">" R1 R2}
	Title = {Fix {Until "" R2 R3}}
	{Const "

" R3 R4}
	choice
	   %% "enchanted" result?
	   {Const "
" R4 R5}
	   {Until "
" R5 R6 _}
	[] %% result with links into document
	   {Const "
" R4 R5}
	   {Until "

" R5 R6 _}
	[] %% PDF file
	   {Const "
" R4 R5}
	   {Until "
" R5 R6 _}
	[] %% With Review
	   {Const "
" R4 R5}
	   R6 = nil %% no nice abstract when a review is there
	[] %% normal result
	   R6 = R4
	end
	Abstract =
	choice
	   {Const "
" R6 R7}
	   {Fix {Until "
" R7 _}}
	[] {Const "
" R6 R7}
	   {Fix {Until "
" R7 _}}
	[] ""
	end
     in
	Root = result(url:Url title:Title content:Abstract)
     end
  in
     {CondSelect {SearchOne Parse} 1 parseError}
  end

  %% Result: contents of Xs until M is found.
  %% Xs = {Append M Yr}
  fun {Until M Xs ?Yr}
     L R
  in
     {List.takeDrop Xs {Length M} L R}
     if L == M then Yr = R nil
     elsecase Xs of X|Xr then X|{Until M Xr Yr}
     [] nil then Yr = nil nil
     end
  end

  %% Asserts that Xs starts with C. Returns the remainder in Ys.
  proc {Const C Xs ?Ys}
     {List.takeDrop Xs {Length C} C Ys}
  end

  %% Assert that a quoted string follows.
  %% Returns the unquoted string and binds Ys to the remainder of Xs.
  fun {QuotedString &"|Xs ?Ys}
     fun {Loop Xs Ys}
	case Xs of &\\|&"|Xr then  &\\|&"|{Loop Xr Ys}
	[] &"|Xr then Ys = Xr nil
	[] X|Xr then X|{Loop Xr Ys}
	end
     end
  in
     {Loop Xs Ys}
  end

  %% Remove formatting tags.
  fun {Fix Xs}
     {Until "
"
      {FoldL ["" "" "<wbr />" "<wbr>" "..."]
       fun {$ Ys Z}
	  {StringX.replace Ys Z ""}
       end
       Xs}
      _}
  end
in
  {ExampleUsage}


/* NetRexx */
options replace format comments java crossref savelog symbols binary

zigzag(5)

return

method zigzag(msize) public static

  row = 1
  col = 1

  ziggy = Rexx(0)
  loop j_ = 0 for msize * msize
    ziggy[row, col] = j_
    if (row + col) // 2 == 0 then do
      if col < msize then -
        col = col + 1
      else row = row + 2
      if row \== 1 then -
        row = row - 1
      end
    else do
      if row < msize then -
        row = row + 1
      else col = col + 2
      if col \== 1 then -
        col = col - 1
      end
    end j_

  L = (msize * msize - 1).length             /*for a constant element width.  */
  loop row = 1 for msize                     /*show all the matrix's rows.    */
    rowOut = ''
    loop col = 1 for msize
      rowOut = rowOut ziggy[row, col].right(L)
      end col
    say rowOut
    end row

  return


var doors = [true] * 100
for (i in 1..100) {
    var j = i
    while (j < 100) {
        doors[j] = !doors[j]
        j = j + i + 1
    }
}

for (i in 0...100) {
    if (doors[i]) System.write("%(i + 1) ")
}
System.print()


USING: accessors assocs colors.constants
combinators.short-circuit io kernel math prettyprint sequences
sets ui ui.gadgets ui.gadgets.charts ui.gadgets.charts.lines ;

: yellowstone? ( n hs seq -- ? )
    {
        [ drop in? not ]
        [ nip last gcd nip 1 = ]
        [ nip dup length 2 - swap nth gcd nip 1 > ]
    } 3&& ;

: next-yellowstone ( hs seq -- n )
    [ 4 ] 2dip [ 3dup yellowstone? ] [ [ 1 + ] 2dip ] until
    2drop ;

: next ( hs seq -- hs' seq' )
    2dup next-yellowstone [ suffix! ] [ pick adjoin ] bi ;

: <yellowstone> ( n -- seq )
    [ HS{ 1 2 3 } clone dup V{ } set-like ] dip dup 3 <=
    [ head nip ] [ 3 - [ next ] times nip ] if ;

! Show first 30 Yellowstone numbers.

"First 30 Yellowstone numbers:" print
30 <yellowstone> [ pprint bl ] each nl

! Plot first 100 Yellowstone numbers.

chart new { { 0 100 } { 0 175 } } >>axes
line new COLOR: blue >>color
100 <iota> 100 <yellowstone> zip >>data
add-gadget "Yellowstone numbers" open-window


: array create cells allot ;
: th cells + ;                         \ some helper words

30 constant #yellow                    \ number of yellowstones

#yellow array y                        \ create array
                                       ( n1 n2 -- n3)
: gcd dup if tuck mod recurse exit then drop ;
: init 3 0 do i 1+ y i th ! loop ;     ( --)
: show cr #yellow 0 do y i th ? loop ; ( --)
: gcd-y[] - cells y + @ over gcd ;     ( k i n -- k gcd )
: loop1 begin 1+ over 2 gcd-y[] 1 = >r over 1 gcd-y[] 1 > r> or 0= until ;
: loop2 over true swap 0 ?do over y i th @ = if 0= leave then loop ;
: yellow #yellow 3 do i 3 begin loop1 loop2 until y rot th ! loop ;
: main init yellow show ;

main


function gcd(a as uinteger, b as uinteger) as uinteger
    if b = 0 then return a
    return gcd( b, a mod b )
end function

dim as uinteger i, j, k, Y(1 to 100)

Y(1) = 1 : Y(2) = 2: Y(3) = 3

for i = 4 to 100
  k = 3
  print i
  do
      k += 1
      if gcd( k, Y(i-2) ) = 1 orelse gcd( k, Y(i-1) ) > 1 then continue do
      for j = 1 to i-1
          if Y(j)=k then continue do
      next j
      Y(i) = k
      exit do
  loop
next i

for i = 1 to 30
    print str(Y(i))+" ";
next i
print
screen 13
for i = 1 to 100
    pset (i, 200-Y(i)), 31
next i

while inkey=""
wend
end


package YahooSearch;

use Encode;
use HTTP::Cookies;
use WWW::Mechanize;

# --- Internals -------------------------------------------------

sub apply (&$)
 {my $f = shift; local $_ = shift; $f->(); return $_;}

# We construct a cookie to get 100 results per page and prevent
# "enhanced results".
my $search_prefs = 'v=1&n=100&sm=' .
    apply {s/([^a-zA-Z0-9])/sprintf '%%%02X', ord $1/ge}
    join '|',
    map {'!' . $_}
    qw(hsb Zq0 XbM sss dDO VFM RQh uZ0 Fxe yCl GP4 FZK yNC mEG niH);
my $cookies = HTTP::Cookies->new;
$cookies->set_cookie(0, 'sB', $search_prefs, '/', 'search.yahoo.com');

my $mech = new WWW::Mechanize
   (cookie_jar => $cookies,
    stack_depth => 0);

sub read_page
 {my ($next, $page, @results) =
     ($mech->find_link(text => 'Next >')->url,
      decode 'iso-8859-1', $mech->content);
  while ($page =~ m
         {<h3> <a \s class="yschttl \s spt" \s
          href=" ([^"]+) " \s* >                #"
          (.+?) </a>
          .+?
          <div \s class="abstr">
          (.+?) </div>}xg)
     {push @results, {url => $1, title => $2, content => $3};
      foreach ( @{$results[-1]}{qw(title content)} )
         {s/<.+?>//g;
          $_ = encode 'utf8', $_;}}
  return $next, \@results;}

# --- Methods ---------------------------------------------------

sub new
 {my $invocant = shift;
  my $class = ref($invocant) || $invocant;
  $mech->get('http://search.yahoo.com/search?p=' . apply
     {s/([^a-zA-Z0-9 ])/sprintf '%%%02X', ord $1/ge;
      s/ /+/g;}
    shift);
  my ($next, $results) = read_page();
  return bless {link_to_next => $next, results => $results}, $class;}

sub results
 {@{shift()->{results}};}

sub next_page
 {my $invocant = shift;
  my $next = $invocant->{link_to_next};
  unless ($next)
     {$invocant->{results} = [];
      return undef;}
  $mech->get($next);
  ($next, my $results) = read_page();
  $invocant->{link_to_next} = $next;
  $invocant->{results} = $results;
  return 1;}


from algorithm import sort
from strutils import align
from sequtils import newSeqWith

type Pos = tuple[x, y: int]

proc `<` (a, b: Pos): bool =
  a.x + a.y < b.x + b.y or
    a.x + a.y == b.x + b.y and (a.x < b.x xor (a.x + a.y) mod 2 == 0)

proc zigzagMatrix(n: int): auto =
  var indices = newSeqOfCap[Pos](n*n)

  for x in 0 ..< n:
    for y in 0 ..< n:
      indices.add((x,y))

  sort(indices)

  result = newSeqWith(n, newSeq[int](n))
  for i, p in indices:
    result[p.x][p.y] = i

proc `$`(m: seq[seq[int]]): string =
  let Width = len($m[0][^1]) + 1
  for r in m:
    for c in r:
      result.add align($c, Width)
    result.add "\n"

echo zigzagMatrix(6)


function : native : ZigZag(size : Int) ~ Int[,] {
  data := Int->New[size, size];
  i := 1;
  j := 1;

  max := size * size;
  for(element := 0; element < max ; element += 1;) {
    data[i - 1, j - 1] := element;

    if((i + j) % 2 = 0) {
      # even stripes
      if(j < size){
        j += 1;
      }
      else{
        i+= 2;
      };

      if(i > 1) {
        i -= 1;
      };
    }
    else{
      # ddd stripes
      if(i < size){
        i += 1;
      }
      else{
        j+= 2;
      };

      if(j > 1){
        j -= 1;
      };
    };
  };

  return data;
}


PROC DrawImage(BYTE ARRAY image BYTE x,y,width,height)
  BYTE i,j
  BYTE POINTER ptr

  Color=2
  FOR j=0 TO height-1
  DO
    Plot(x,j+y) DrawTo(x+width-1,j+y)
  OD
  Color=1
  ptr=image
  FOR j=0 TO height-1
  DO
    FOR i=0 TO width-1
    DO
      IF ptr^ THEN
        Plot(i+x,j+y)
      FI
      ptr==+1
    OD
  OD
RETURN

PROC Thinning(BYTE ARRAY image BYTE width,height)
  DEFINE PTR="CARD"
  DEFINE MAX="200"
  PTR ARRAY change(MAX)
  BYTE POINTER p1,p2,p3,p4,p5,p6,p7,p8,p9,p68,p24
  INT count,i
  BYTE x,y,sum,step1

  step1=1
  DO
    count=0
    p1=image p8=p1-1 p4=p1+1
    p2=p1-width p6=p1+width
    p9=p2-1 p3=p2+1
    p7=p6-1 p5=p6+1

    FOR y=0 TO height-1
    DO
      FOR x=0 TO width-1
      DO
        IF p1^=1 AND x>0 AND y>0 AND x<width-1 AND y<height-1 THEN
          sum=p2^+p3^+p4^+p5^+p6^+p7^+p8^+p9^
          IF sum>=2 AND sum<=6 THEN
            sum=0
            IF p3^>p2^ THEN sum==+1 FI
            IF p4^>p3^ THEN sum==+1 FI
            IF p5^>p4^ THEN sum==+1 FI
            IF p6^>p5^ THEN sum==+1 FI
            IF p7^>p6^ THEN sum==+1 FI
            IF p8^>p7^ THEN sum==+1 FI
            IF p9^>p8^ THEN sum==+1 FI
            IF p2^>p9^ THEN sum==+1 FI
            IF sum=1 THEN
              IF step1 THEN
                p24=p4 p68=p6
              ELSE
                p24=p2 p68=p8
              FI
              IF p2^+p4^+p68^<3 AND p24^+p6^+p8^<3 THEN
                change(count)=p1 count==+1
              FI
            FI
          FI
        FI
        p1==+1 p2==+1 p3==+1 p4==+1 p5==+1
        p6==+1 p7==+1 p8==+1 p9==+1
      OD
    OD
    step1=1-step1
    FOR i=0 TO count-1
    DO
      p1=change(i) p1^=0
    OD
  UNTIL count=0
  OD
RETURN

PROC Main()
  BYTE ARRAY image1=[
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0
    0 1 1 1 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0
    0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0
    0 1 1 1 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0
    0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 1 1 1 0 0 1 1 1 1 0 1 1 1 0 0
    0 1 1 1 0 0 0 1 1 1 1 0 1 1 1 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  BYTE ARRAY image2=[
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
    0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
    0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
    0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
    0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
    0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
    0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
    0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0
    0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0
    0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  BYTE width1=[32],height1=[10],width2=[59],height2=[18]
  BYTE CH=$02FC

  Graphics(7+16)
  Color=1
  SetColor(0,0,$00)
  SetColor(4,0,$04)
  SetColor(1,0,$0C)

  DrawImage(image1,0,0,width1,height1)
  Thinning(image1,width1,height1)
  DrawImage(image1,width1+10,0,width1,height1)

  DrawImage(image2,0,height1+10,width2,height2)
  Thinning(image2,width2,height2)
  DrawImage(image2,width2+10,height1+10,width2,height2)

  DO UNTIL CH#$FF OD
  CH=$FF
RETURN


-- Params:
-- List of lists (rows) of "pixel" values.
-- Record indicating the values representing black and white.
on ZhangSuen(matrix, {black:black, white:white})
    script o
        property matrix : missing value
        property changePixels : missing value

        on A(neighbours) -- Count transitions from white to black.
            set sum to 0
            repeat with i from 1 to 8
                if ((neighbours's item i is white) and (neighbours's item (i mod 8 + 1) is black)) then set sum to sum + 1
            end repeat
            return sum
        end A

        on B(neighbours) -- Count neighbouring black pixels.
            set sum to 0
            repeat with p in neighbours
                if (p's contents is black) then set sum to sum + 1
            end repeat
            return sum
        end B
    end script

    set o's matrix to matrix
    set rowCount to (count o's matrix)
    set columnCount to (count o's matrix's beginning) -- Assumed to be the same for every row.
    repeat until (o's changePixels is {})
        repeat with step from 1 to 2
            set o's changePixels to {}
            repeat with r from 2 to (rowCount - 1)
                repeat with c from 2 to (columnCount - 1)
                    if (o's matrix's item r's item c is black) then
                        tell (a reference to o's matrix) to ¬
                            set neighbours to {item (r - 1)'s item c, item (r - 1)'s item (c + 1), ¬
                                item r's item (c + 1), item (r + 1)'s item (c + 1), item (r + 1)'s item c, ¬
                                item (r + 1)'s item (c - 1), item r's item (c - 1), item (r - 1)'s item (c - 1)}
                        set blackCount to o's B(neighbours)
                        if ((blackCount > 1) and (blackCount < 7) and (o's A(neighbours) is 1)) then
                            set {P2, x, P4, x, P6, x, P8} to neighbours
                            if (step is 1) then
                                set toChange to ((P4 is white) or (P6 is white) or ((P2 is white) and (P8 is white)))
                            else
                                set toChange to ((P2 is white) or (P8 is white) or ((P4 is white) and (P6 is white)))
                            end if
                            if (toChange) then set end of o's changePixels to {r, c}
                        end if
                    end if
                end repeat
            end repeat
            if (o's changePixels is {}) then exit repeat
            repeat with pixel in o's changePixels
                set {r, c} to pixel
                set o's matrix's item r's item c to white
            end repeat
        end repeat
    end repeat

    return o's matrix -- or: return matrix -- The input has been edited in place.
end ZhangSuen

on join(lst, delim)
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to delim
    set txt to lst as text
    set AppleScript's text item delimiters to astid
    return txt
end join

on demo()
    set pattern to "00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000"
    set matrix to pattern's paragraphs
    repeat with thisRow in matrix
        set thisRow's contents to thisRow's characters
    end repeat
    ZhangSuen(matrix, {black:"1", white:"0"})
    repeat with thisRow in matrix
        set thisRow's contents to join(thisRow, "")
    end repeat
    return join(matrix, linefeed)
end demo
return demo()


		.NOLIST

; The task can be completed in 48 and "half" steps:
; On the first pass ALL doors are opened.
; On the second pass every EVEN door is closed.
; So, instead of all closed, the doors can initially be:
; Every odd door open, every even door closed and start at pass 3.
; On 51st and all the next passes, only one door is visited per pass:
; On 51st pass door 51, on 52nd pass door 52 etc.
; So, after pass 50, we can make "half a pass" starting with door 51
; and toggling every door up to and including 100.
; The code uses only volatile registers, so, no string (STOS etc) instructions.

		TITLE	100 Doors
		PAGE	, 132
		.686
		.MODEL	FLAT
		OPTION	CASEMAP:NONE

		.SFCOND
		.LIST

; =============================================================================

		.DATA?

Doors		BYTE	100 DUP ( ? )

; =============================================================================

		.CODE

Pass_Doors	PROC

		MOV	EDX, OFFSET Doors	; Initialize all doors.
		MOV	ECX, SIZEOF Doors / SIZEOF DWORD
		MOV	EAX, 01010101h		; This does first and second pass.

Close_Doors:	MOV	[ EDX ], EAX
		ADD	EDX, SIZEOF DWORD
		LOOP	Close_Doors

		MOV	ECX, 2			; Pass and step.

Pass_Loop:	MOV	EDX, OFFSET Doors

		ASSUME	EDX:PTR BYTE

Doors_Loop:	XOR	[ EDX ], 1		; Toggle this door.
		ADD	EDX, ECX                ; Advance.
		CMP	EDX, OFFSET Doors[ SIZEOF Doors ]

		JB	Doors_Loop

		INC	ECX
		CMP	ECX, SIZEOF Doors

		JB	Pass_Loop

		XOR	Doors[ SIZEOF Doors -1 ], 1 ; This is pass 100.
		RET

Pass_Doors	ENDP

; =============================================================================

		END


package main

import (
    "fmt"
    "log"
    "os/exec"
)

func gcd(x, y int) int {
    for y != 0 {
        x, y = y, x%y
    }
    return x
}

func yellowstone(n int) []int {
    m := make(map[int]bool)
    a := make([]int, n+1)
    for i := 1; i < 4; i++ {
        a[i] = i
        m[i] = true
    }
    min := 4
    for c := 4; c <= n; c++ {
        for i := min; ; i++ {
            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {
                a[c] = i
                m[i] = true
                if i == min {
                    min++
                }
                break
            }
        }
    }
    return a[1:]
}

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    x := make([]int, 100)
    for i := 0; i < 100; i++ {
        x[i] = i + 1
    }
    y := yellowstone(100)
    fmt.Println("The first 30 Yellowstone numbers are:")
    fmt.Println(y[:30])
    g := exec.Command("gnuplot", "-persist")
    w, err := g.StdinPipe()
    check(err)
    check(g.Start())
    fmt.Fprintln(w, "unset key; plot '-'")
    for i, xi := range x {
        fmt.Fprintf(w, "%d %d\n", xi, y[i])
    }
    fmt.Fprintln(w, "e")
    w.Close()
    g.Wait()
}


constant glyphs = {{"\xC2\xB7 ","*"},                -- bullet point
                   {"'",`'`},		     -- single quote
                   {""",`"`},		     -- double quote
                   {"&","&"},                    -- ampersand
                   {"\xE2\x94\xAC\xC2\xAB","[R]"},   -- registered
                   {"\xC2\xAE","[R]"}},              -- registered


(load "@lib/http.l")

(de yahoo (Query Page)
   (default Page 1)
   (client "search.yahoo.com" 80
      (pack
         "search?p=" (ht:Fmt Query)
         "&b=" (inc (* 10 (dec Page))) )
      (make
         (while (from "<a class=\"yschttl spt\" href=\"")
            (link
               (make
                  (link (till "\"" T))       # Url
                  (from "<b>")
                  (link (till "<" T))        # Title
                  (from "class=\"abstr\"")
                  (from ">")
                  (link                      # Content
                     (pack
                        (make
                           (loop
                              (link (till "<" T))
                              (T (eof))
                              (T (= "</div" (till ">" T)))
                              (char) ) ) ) ) ) ) ) ) ) )


import urllib
import re

def fix(x):
    p = re.compile(r'<[^<]*?>')
    return p.sub('', x).replace('&', '&')

class YahooSearch:
    def __init__(self, query, page=1):
        self.query = query
        self.page = page
        self.url = "http://search.yahoo.com/search?p=%s&b=%s" %(self.query, ((self.page - 1) * 10 + 1))
        self.content = urllib.urlopen(self.url).read()

    def getresults(self):
        self.results = []

        for i in re.findall('(.+?)

(.+?)
.*?(.+?)', self.content):

            title = fix(i[0])
            content = fix(i[1])
            url = fix(i[2])

            self.results.append(YahooResult(title, content, url))

        return self.results

    def getnextpage(self):
        return YahooSearch(self.query, self.page+1)

    search_results = property(fget=getresults)
    nextpage = property(fget=getnextpage)

class YahooResult:
    def __init__(self,title,content,url):
        self.title = title
        self.content = content
        self.url = url

# Usage:

x = YahooSearch("test")

for result in x.search_results:
    print result.title


let zigzag n =
  (* move takes references and modifies them directly *)
  let move i j =
    if !j < n - 1 then begin
      i := max 0 (!i - 1);
      incr j
    end else
      incr i
  in
  let a = Array.make_matrix n n 0
  and x = ref 0 and y = ref 0 in
  for v = 0 to n * n - 1 do
    a.(!x).(!y) <- v;
    if (!x + !y) mod 2 = 0 then
      move x y
    else
      move y x
  done;
  a


FileIn  := A_ScriptDir "\Zhang-Suen.txt"
FileOut := A_ScriptDir "\NewFile.txt"

if (!FileExist(FileIn)) {
	MsgBox, 48, File Not Found, % "File """ FileIn """ not found."
	ExitApp
}
S := {}
N := [2,3,4,5,6,7,8,9,2]

Loop, Read, % FileIn
{
	LineNum := A_Index
	Loop, Parse, A_LoopReadLine
		S[LineNum, A_Index] := A_LoopField
}

Loop {
	FlipCount := 0
	Loop, 2 {
		Noted := [], i := A_Index
		for LineNum, Line in S {
			for PixNum, Pix in Line {
			; (0)
				if (Pix = 0 || (P := GetNeighbors(LineNum, PixNum, S)) = 1)
					continue
			; (1)
				BP := 0
				for j, Val in P
					BP += Val
				if (BP < 2 || BP > 6)
					continue
			; (2)
				AP := 0
				Loop, 8
					if (P[N[A_Index]] = "0" && P[N[A_Index + 1]] = "1")
						AP++
				if (AP != 1)
					continue
			; (3 and 4)
				if (i = 1) {
					if (P[2] + P[4] + P[6] = 3 || P[4] + P[6] + P[8] = 3)
						continue
				}
				else if (P[2] + P[4] + P[8] = 3 || P[2] + P[6] + P[8] = 3)
					continue

				Noted.Insert([LineNum, PixNum])
				FlipCount++
			}
		}
		for j, Coords in Noted
			S[Coords[1], Coords[2]] := 0
	}
	if (!FlipCount)
		break
}

for LineNum, Line in S {
	for PixNum, Pix in Line
		Out .= Pix ? "#" : " "
	Out .= "`n"
}
FileAppend, % Out, % FileOut

GetNeighbors(Y, X, S) {
	Neighbors := []
	if ((Neighbors[8] := S[Y, X - 1]) = "")
		return 1
	if ((Neighbors[4] := S[Y, X + 1]) = "")
		return 1
	Loop, 3
		if ((Neighbors[A_Index = 1 ? 9 : A_Index] := S[Y - 1, X - 2 + A_Index]) = "")
			return 1
	Loop, 3
		if ((Neighbors[8 - A_Index] := S[Y + 1, X - 2 + A_Index]) = "")
			return 1
	return Neighbors
}


PROGRAM "100doors"
VERSION "0.0001"

IMPORT "xma"
IMPORT "xst"

DECLARE FUNCTION Entry()

FUNCTION Entry()
  maxpuertas = 100
  cont = 0
  DIM puertas[100]

  FOR p = 1 TO maxpuertas
    IF INT(SQRT(p)) = SQRT(p) THEN puertas[p] = 1
  NEXT p

  PRINT "The doors are open: ";
  FOR p = 1 TO maxpuertas
    IF puertas[p] = 1 THEN
       PRINT p; " ";
       INC cont
    END IF
  NEXT p

  PRINT CHR$(10); "Are "; STR$(cont); " open doors."

END FUNCTION
END PROGRAM


import Data.List (unfoldr)

yellowstone :: [Integer]
yellowstone = 1 : 2 : 3 : unfoldr (Just . f) (2, 3, [4 ..])
  where
    f ::
      (Integer, Integer, [Integer]) ->
      (Integer, (Integer, Integer, [Integer]))
    f (p2, p1, rest) = (next, (p1, next, rest_))
      where
        (next, rest_) = select rest
        select :: [Integer] -> (Integer, [Integer])
        select (x : xs)
          | gcd x p1 == 1 && gcd x p2 /= 1 = (x, xs)
          | otherwise = (y, x : ys)
          where
            (y, ys) = select xs

main :: IO ()
main = print $ take 30 yellowstone


Until=: 2 :'u^:(0-:v)^:_'
assert 44 -: >:Until(>&43) 32  NB. increment until exceeding 43
gcd=: +.
coprime=: 1 = gcd
prepare=:1 2 3"_   NB. start with the vector 1 2 3
condition=: 0 1 -: (coprime _2&{.)   NB. trial coprime most recent 2,  nay and yay
append=: ,      NB. concatenate
novel=: [email protected]   NB. x is not a member of y
term=: >:@:]Until((condition *. novel)~) 4:
ys=: (append term)@]^:(0 >. _3+[) prepare
assert (ys 30) -: 1 2 3 4 9 8 15 14 5 6 25 12 35 16 7 10 21 20 27 22 39 11 13 33 26 45 28 51 32 17


YahooSearch <- function(query, page=1, .opts=list(), ignoreMarkUpErrors=TRUE)
{
   if(!require(RCurl) || !require(XML))
   {
      stop("Could not load required packages")
   }

   # Replace " " with "%20", etc
   query <- curlEscape(query)

   # Retrieve page
   b <- 10*(page-1)+1
   theurl <- paste("http://uk.search.yahoo.com/search?p=",
      query, "&b=", b, sep="")
   webpage <- getURL(theurl, .opts=.opts)

   # Save search for nextpage function
   .Search <- list(query=query, page=page, .opts=.opts,
      ignoreMarkUpErrors=ignoreMarkUpErrors)
   assign(".Search", .Search, envir=globalenv())

   # Parse HTML; retrieve results block
   webpage <- readLines(tc <- textConnection(webpage)); close(tc)
   if(ignoreMarkUpErrors)
   {
      pagetree <- htmlTreeParse(webpage, error=function(...){})
   } else
   {
      pagetree <- htmlTreeParse(webpage)
   }

   findbyattr <- function(x, id, type="id")
   {
      ids <- sapply(x, function(x) x$attributes[type])
      x[ids==id]
   }

   body <- pagetree$children$html$children$body
   bd <- findbyattr(body$children$div$children, "bd")
   left <- findbyattr(bd$div$children$div$children, "left")
   web <- findbyattr(left$div$children$div$children, "web")
   resol <- web$div$children$ol

   #Get url, title, content from results
   gettextfromnode <- function(x)
   {
      un <- unlist(x$children)
      paste(un[grep("value", names(un))], collapse=" ")
   }

   n <- length(resol)
   results <- list()
   length(results) <- n
   for(i in 1:n)
   {
      mainlink <- resol[[i]]$children$div$children[1]$div$children$h3$children$a
      url <- mainlink$attributes["href"]
      title <- gettextfromnode(mainlink)

      contenttext <- findbyattr(resol[[i]]$children$div$children[2], "abstr", type="class")
      if(length(contenttext)==0)
      {
          contenttext <- findbyattr(resol[[i]]$children$div$children[2]$div$children$div$children,
            "sm-abs", type="class")
      }

      content <- gettextfromnode(contenttext$div)
      results[[i]] <- list(url=url, title=title, content=content)
   }
   names(results) <- as.character(seq(b, b+n-1))
   results
}

nextpage <- function()
{
   if(exists(".Search", envir=globalenv()))
   {
      .Search <- get(".Search", envir=globalenv())
      .Search$page  <- .Search$page + 1L
      do.call(YahooSearch, .Search)
   } else
   {
      message("No search has been performed yet")
   }
}

#Usage
YahooSearch("rosetta code")
nextpage()


#lang racket
(require net/url)
(define *yaho-url* "http://search.yahoo.com/search?p=~a&b=~a")
(define *current-page* 0)
(define *current-query* "")
(define request (compose port->string get-pure-port string->url))

;;strip html tags
(define (remove-tags text)
  (regexp-replace* #px"<[^<]+?>" text ""))

;;search, parse and print
(define (search-yahoo query)
  (unless (string=? *current-query* query) ;different query, go back to page 1
    (set! *current-query* query)
    (set! *current-page* 0))
  (let* ([current-page (number->string (add1 (* 10 *current-page*)))]
         [html (request (format *yaho-url* query current-page))]
         [results (regexp-match* #px"lass=\"yschttl spt\" href=\".+?\">(.+?)(.+?).+?
(.+?)
" html #:match-select cdr)])
    (for ([result (in-list results)])
      (printf "Title: ~a \n Link: ~a \n Text: ~a \n\n"
              (remove-tags (first result))
              (remove-tags (second result) )
              (remove-tags (third result))))))

;;search nexxt page
(define (next-page)
  (set! *current-page* (add1 *current-page*))
  (search-yahoo *current-query*))


use Gumbo;
use LWP::Simple;
use XML::Text;

class YahooSearch {
  has $!dom;

  submethod BUILD (:$!dom) { }

  method new($term) {
    self.bless(
      dom => parse-html(
        LWP::Simple.get("http://search.yahoo.com/search?p={ $term }")
      )
    );
  }

  method next {
    $!dom = parse-html(
      LWP::Simple.get(
        $!dom.lookfor( TAG => 'a', class => 'next' ).head.attribs<href>
      )
    );
    self;
  }

  method text ($node) {
    return ''         unless $node;
    return $node.text if     $node ~~ XML::Text;

    $node.nodes.map({ self.text($_).trim }).join(' ');
  }

  method results {
    state $n = 0;
    for $!dom.lookfor( TAG => 'h3', class => 'title') {
      given .lookfor( TAG => 'a' )[0] {
        next unless $_;                                               # No Link
        next if .attribs<href> ~~ / ^ 'https://r.search.yahoo.com' /; # Ad
        say "=== #{ ++$n } ===";
        say "Title: { .contents[0] ?? self.text( .contents[0] ) !! '' }";
        say "  URL: { .attribs<href> }";

        my $pt = .parent.parent.parent.elements( TAG => 'div' ).tail;
        say " Text: { self.text($pt) }";
      }
    }
    self;
  }

}

sub MAIN (Str $search-term) is export {
  YahooSearch.new($search-term).results.next.results;
}


<Rows> <Columns>
<Blank pixel character> <Image Pixel character>
<Image of specified rows and columns made up of the two pixel types specified in the second line.>


// True=Open; False=Closed
Dim doors(100) As Boolean // Booleans default to false
For j As Integer = 1 To 100
  For i As Integer = 1 to 100
    If i Mod j = 0 Then doors(i) = Not doors(i)
  Next
Next


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

public class YellowstoneSequence {

    public static void main(String[] args) {
         System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30));
    }

    private static List<Integer> yellowstoneSequence(int sequenceCount) {
        List<Integer> yellowstoneList = new ArrayList<Integer>();
        yellowstoneList.add(1);
        yellowstoneList.add(2);
        yellowstoneList.add(3);
        int num = 4;
        List<Integer> notYellowstoneList = new ArrayList<Integer>();
        int yellowSize = 3;
        while ( yellowSize < sequenceCount ) {
            int found = -1;
            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {
                int test = notYellowstoneList.get(index);
                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {
                    found = index;
                    break;
                }
            }
            if ( found >= 0 ) {
                yellowstoneList.add(notYellowstoneList.remove(found));
                yellowSize++;
            }
            else {
                while ( true ) {
                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {
                        yellowstoneList.add(num);
                        yellowSize++;
                        num++;
                        break;
                    }
                    notYellowstoneList.add(num);
                    num++;
                }
            }
        }
        return yellowstoneList;
    }

    private static final int gcd(int a, int b) {
        if ( b == 0 ) {
            return a;
        }
        return gcd(b, a%b);
    }

}


require 'open-uri'
require 'hpricot'

SearchResult = Struct.new(:url, :title, :content)

class SearchYahoo
  @@urlinfo = [nil, 'ca.search.yahoo.com', 80, '/search', nil, nil]

  def initialize(term)
    @term = term
    @page = 1
    @results = nil
    @url = URI::HTTP.build(@@urlinfo)
  end

  def next_result
    if not @results
      @results = []
      fetch_results
    elsif @results.empty?
      next_page
    end
    @results.shift
  end

  def fetch_results
    @url.query = URI.escape("p=%s&b=%d" % [@term, @page])
    doc = open(@url) { |f| Hpricot(f) }
    parse_html(doc)
  end

  def next_page
    @page += 10
    fetch_results
  end

  def parse_html(doc)
    doc.search("div#main").search("div").each do |div|
      next unless div.has_attribute?("class") and div.get_attribute("class").index("res") == 0
      result = SearchResult.new
      div.search("a").each do |link|
        next unless link.has_attribute?("class") and link.get_attribute("class") == "yschttl spt"
        result.url = link.get_attribute("href")
        result.title = link.inner_text
      end
      div.search("div").each do |abstract|
        next unless abstract.has_attribute?("class") and abstract.get_attribute("class").index("abstr")
        result.content = abstract.inner_text
      end
      @results << result
    end
  end
end

s = SearchYahoo.new("test")
15.times do |i|
  result = s.next_result
  puts i+1
  puts result.title
  puts result.url
  puts result.content
  puts
end


#{
  Produce a zigzag matrix. Nigel Galloway, January 26th., 2020.
  At the time of writing the Rascal solution is yellow flagged for producing a striped matrix.
  Let me make the same faux pas.
#}
n=5; g=1;
for e=1:n i=1; for l=e:-1:1 zig(i++,l)=g++; endfor endfor
for e=2:n i=e; for l=n:-1:e zig(i++,l)=g++; endfor endfor
#{
  I then have the following, let me call it zig.
    1    2    4    7   11
    3    5    8   12   16
    6    9   13   17   20
   10   14   18   21   23
   15   19   22   24   25

  To avoid being yellow flagged I must convert this striped matrix into a zigzag matrix.
#}
zag=zig'
#{
  So zag is the transpose of zig.
    1    3    6   10   15
    2    5    9   14   19
    4    8   13   18   22
    7   12   17   21   24
   11   16   20   23   25
#}
for e=1:n for g=1:n if(mod(e+g,2))==0 zagM(e,g)=1; endif endfor endfor; zigM=1-zagM;
#{
  I now have 2 masks:

  zigM =

   0   1   0   1   0
   1   0   1   0   1
   0   1   0   1   0
   1   0   1   0   1
   0   1   0   1   0

  zagM =

   1   0   1   0   1
   0   1   0   1   0
   1   0   1   0   1
   0   1   0   1   0
   1   0   1   0   1
#}
zigzag=zag.*zagM+zig.*zigM;
#{
  zigzag =

    1    2    6    7   15
    3    5    8   14   16
    4    9   13   17   22
   10   12   18   21   23
   11   19   20   24   25
#}


import std.stdio, std.algorithm, std.string, std.functional,
       std.typecons, std.typetuple, bitmap;

struct BlackWhite {
    ubyte c;
    alias c this;
    static immutable black = typeof(this)(0),
                     white = typeof(this)(1);
}

alias Neighbours = BlackWhite[9];
alias Img = Image!BlackWhite;

/// Zhang-Suen thinning algorithm.
Img zhangSuen(Img image1, Img image2) pure nothrow @safe @nogc
in {
    assert(image1.image.all!(x => x == Img.black || x == Img.white));
    assert(image1.nx == image2.nx && image1.ny == image2.ny);
} out(result) {
    assert(result.nx == image1.nx && result.ny == image1.ny);
    assert(result.image.all!(x => x == Img.black || x == Img.white));
} body {
    /// True if inf <= x <= sup.
    static inInterval(T)(in T x, in T inf, in T sup) pure nothrow @safe @nogc {
        return x >= inf && x <= sup;
    }

    /// Return 8-neighbours+1 of point (x,y) of given image, in order.
    static void neighbours(in Img I, in size_t x, in size_t y,
                           out Neighbours n) pure nothrow @safe @nogc {
        n = [I[x,y-1], I[x+1,y-1], I[x+1,y], I[x+1,y+1], // P2,P3,P4,P5
             I[x,y+1], I[x-1,y+1], I[x-1,y], I[x-1,y-1], // P6,P7,P8,P9
             I[x,y-1]];
    }

    if (image1.nx < 3 || image1.ny < 3) {
        image2.image[] = image1.image[];
        return image2;
    }

    immutable static zeroOne = [0, 1]; //**
    Neighbours n;
    bool hasChanged;
    do {
        hasChanged = false;

        foreach (immutable ab; TypeTuple!(tuple(2, 4), tuple(0, 6))) {
            foreach (immutable y; 1 .. image1.ny - 1) {
                foreach (immutable x; 1 .. image1.nx - 1) {
                    neighbours(image1, x, y, n);
                    if (image1[x, y] &&                    // Cond. 0
                        (!n[ab[0]] || !n[4] || !n[6]) &&   // Cond. 4
                        (!n[0] || !n[2] || !n[ab[1]]) &&   // Cond. 3
                        //n[].count([0, 1]) == 1 &&
                        n[].count(zeroOne) == 1 &&         // Cond. 2
                        // n[0 .. 8].sum in iota(2, 7)) {
                        inInterval(n[0 .. 8].sum, 2, 6)) { // Cond. 1
                        hasChanged = true;
                        image2[x, y] = Img.black;
                    } else
                        image2[x, y] = image1[x, y];
                }
            }
            image1.swap(image2);
        }
    } while (hasChanged);

    return image1;
}

void main() {
    immutable before_txt = "
    ##..###
    ##..###
    ##..###
    ##..###
    ##..##.
    ##..##.
    ##..##.
    ##..##.
    ##..##.
    ##..##.
    ##..##.
    ##..##.
    ######.
    .......";

    immutable small_rc = "
    ................................
    .#########.......########.......
    .###...####.....####..####......
    .###....###.....###....###......
    .###...####.....###.............
    .#########......###.............
    .###.####.......###....###......
    .###..####..###.####..####.###..
    .###...####.###..########..###..
    ................................";

    immutable rc = "
    ...........................................................
    .#################...................#############.........
    .##################...............################.........
    .###################............##################.........
    .########.....#######..........###################.........
    ...######.....#######.........#######.......######.........
    ...######.....#######........#######.......................
    ...#################.........#######.......................
    ...################..........#######.......................
    ...#################.........#######.......................
    ...######.....#######........#######.......................
    ...######.....#######........#######.......................
    ...######.....#######.........#######.......######.........
    .########.....#######..........###################.........
    .########.....#######.######....##################.######..
    .########.....#######.######......################.######..
    .########.....#######.######.........#############.######..
    ...........................................................";

    foreach (immutable txt; [before_txt, small_rc, rc]) {
        auto img = Img.fromText(txt);
        "From:".writeln;
        img.textualShow(/*bl=*/ '.', /*wh=*/ '#');
        "\nTo thinned:".writeln;
        img.zhangSuen(img.dup).textualShow(/*bl=*/ '.', /*wh=*/ '#');
        writeln;
    }
}


include c:\cxpl\codes;          \intrinsic 'code' declarations
int     Door(100);              \You have 100 doors in a row
define  Open, Closed;
int     D, Pass, Step;

[for D:= 0 to 100-1 do          \that are all initially closed
        Door(D):= Closed;

Step:= 1;                       \The first time through, you visit every door
for Pass:= 1 to 100 do          \You make 100 passes by the doors
        [D:= Step-1;
        repeat  \if the door is closed, you open it; if it is open, you close it
                if Door(D)=Closed then Door(D):= Open else Door(D):= Closed;
                D:= D+Step;
        until   D>=100;
        Step:= Step+1;          \The second time you only visit every 2nd door
        ];                      \The third time, every 3rd door
                                \until you only visit the 100th door
\What state are the doors in after the last pass?
Text(0, "Open: ");              \Which are open?
for D:= 0 to 100-1 do
        if Door(D)=Open then [IntOut(0, D+1); ChOut(0,^ )];
CrLf(0);

Text(0, "Closed: ");            \Which are closed?
for D:= 0 to 100-1 do
        if Door(D)=Closed then [IntOut(0, D+1); ChOut(0,^ )];
CrLf(0);

\Optimized: The only doors that remain open are those that are perfect squares
Text(0, "Open: ");
D:= 1;
repeat  IntOut(0, D*D); ChOut(0,^ );
        D:= D+1;
until   D*D>100;
CrLf(0);
]


(() => {
    'use strict';

    // yellowstone :: Generator [Int]
    function* yellowstone() {
        // A non finite stream of terms in the
        // Yellowstone permutation of the natural numbers.
        // OEIS A098550
        const nextWindow = ([p2, p1, rest]) => {
            const [rp2, rp1] = [p2, p1].map(
                relativelyPrime
            );
            const go = xxs => {
                const [x, xs] = Array.from(
                    uncons(xxs).Just
                );
                return rp1(x) && !rp2(x) ? (
                    Tuple(x)(xs)
                ) : secondArrow(cons(x))(
                    go(xs)
                );
            };
            return [p1, ...Array.from(go(rest))];
        };
        const A098550 = fmapGen(x => x[1])(
            iterate(nextWindow)(
                [2, 3, enumFrom(4)]
            )
        );
        yield 1
        yield 2
        while (true)(
            yield A098550.next().value
        )
    };

    // relativelyPrime :: Int -> Int -> Bool
    const relativelyPrime = a =>
        // True if a is relatively prime to b.
        b => 1 === gcd(a)(b);

    // ------------------------TEST------------------------
    const main = () => console.log(
        take(30)(
            yellowstone()
        )
    );

    // -----------------GENERIC FUNCTIONS------------------

    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a =>
        b => ({
            type: 'Tuple',
            '0': a,
            '1': b,
            length: 2
        });

    // abs :: Num -> Num
    const abs =
        // Absolute value of a given number - without the sign.
        Math.abs;

    // cons :: a -> [a] -> [a]
    const cons = x =>
        xs => Array.isArray(xs) ? (
            [x].concat(xs)
        ) : 'GeneratorFunction' !== xs
        .constructor.constructor.name ? (
            x + xs
        ) : ( // cons(x)(Generator)
            function*() {
                yield x;
                let nxt = xs.next()
                while (!nxt.done) {
                    yield nxt.value;
                    nxt = xs.next();
                }
            }
        )();

    // enumFrom :: Enum a => a -> [a]
    function* enumFrom(x) {
        // A non-finite succession of enumerable
        // values, starting with the value x.
        let v = x;
        while (true) {
            yield v;
            v = 1 + v;
        }
    }

    // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
    const fmapGen = f =>
        function*(gen) {
            let v = take(1)(gen);
            while (0 < v.length) {
                yield(f(v[0]))
                v = take(1)(gen)
            }
        };

    // gcd :: Int -> Int -> Int
    const gcd = x => y => {
        const
            _gcd = (a, b) => (0 === b ? a : _gcd(b, a % b)),
            abs = Math.abs;
        return _gcd(abs(x), abs(y));
    };

    // iterate :: (a -> a) -> a -> Gen [a]
    const iterate = f =>
        function*(x) {
            let v = x;
            while (true) {
                yield(v);
                v = f(v);
            }
        };

    // length :: [a] -> Int
    const length = xs =>
        // Returns Infinity over objects without finite
        // length. This enables zip and zipWith to choose
        // the shorter argument when one is non-finite,
        // like cycle, repeat etc
        (Array.isArray(xs) || 'string' === typeof xs) ? (
            xs.length
        ) : Infinity;

    // secondArrow :: (a -> b) -> ((c, a) -> (c, b))
    const secondArrow = f => xy =>
        // A function over a simple value lifted
        // to a function over a tuple.
        // f (a, b) -> (a, f(b))
        Tuple(xy[0])(
            f(xy[1])
        );

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n =>
        // The first n elements of a list,
        // string of characters, or stream.
        xs => 'GeneratorFunction' !== xs
        .constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

    // uncons :: [a] -> Maybe (a, [a])
    const uncons = xs => {
        // Just a tuple of the head of xs and its tail,
        // Or Nothing if xs is an empty list.
        const lng = length(xs);
        return (0 < lng) ? (
            Infinity > lng ? (
                Just(Tuple(xs[0])(xs.slice(1))) // Finite list
            ) : (() => {
                const nxt = take(1)(xs);
                return 0 < nxt.length ? (
                    Just(Tuple(nxt[0])(xs))
                ) : Nothing();
            })() // Lazy generator
        ) : Nothing();
    };

    // MAIN ---
    return main();
})();


package require http

proc fix s {
    string map {... ""  ""  "" <wbr> "" "<wbr />" ""} \
            [regsub "

.*" $s ""]
}
proc YahooSearch {term {page 1}} {
    # Build the (ugly) scraper URL
    append re {(.+?)
}
    append re {

(.+?)}
    append re {
(.+?)}

    # Perform the query; note that this handles special characters
    # in the query term correctly
    set q [http::formatQuery p $term b [expr {$page*10-9}]]
    set token [http::geturl http://search.yahoo.com/search?$q]
    set data [http::data $token]
    http::cleanup $token

    # Assemble the results into a nice list
    set results {}
    foreach {- title content url} [regexp -all -inline $re $data] {
        lappend results [fix $title] [fix $content] [fix $url]
    }

    # set up the call for the next page
    interp alias {} Nextpage {} YahooSearch $term [incr page]

    return $results
}

# Usage:  get the first two pages of results
foreach {title content url} [YahooSearch "test"] {
    puts $title
}
foreach {title content url} [Nextpage] {
     puts $title
}


call printArray zigzag(3)
say
call printArray zigzag(4)
say
call printArray zigzag(5)

::routine zigzag
  use strict arg size

  data = .array~new(size, size)
  row = 1
  col = 1

  loop element = 0 to (size * size) - 1
      data[row, col] = element
      -- even stripes
      if (row + col) // 2 = 0 then do
          if col < size then col += 1
          else row += 2
          if row > 1 then row -= 1
      end
      -- odd rows
      else do
          if row < size then row += 1
          else col += 2
          if col > 1 then col -= 1
      end
  end

  return data

::routine printArray
  use arg array
  dimension = array~dimension(1)
  loop i = 1 to dimension
      line = "|"
      loop j = 1 to dimension
          line = line array[i, j]~right(2)
      end
      line = line "|"
      say line
   end


defmodule ZhangSuen do
  @neighbours  [{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}]  # 8 neighbours

  def thinning(str, black \\ ?#) do
    s0 = for {line, i} <- (String.split(str, "\n") |> Enum.with_index),
             {c, j}    <- (to_char_list(line) |> Enum.with_index),
             into: Map.new,
             do: {{i,j}, (if c==black, do: 1, else: 0)}
    {xrange, yrange} = range(s0)
    print(s0, xrange, yrange)
    s1 = thinning_loop(s0, xrange, yrange)
    print(s1, xrange, yrange)
  end

  defp thinning_loop(s0, xrange, yrange) do
    s1 = step(s0, xrange, yrange, 1)            # Step 1
    s2 = step(s1, xrange, yrange, 0)            # Step 2
    if Map.equal?(s0, s2), do: s2, else: thinning_loop(s2, xrange, yrange)
  end

  defp step(s, xrange, yrange, g) do
    for x <- xrange, y <- yrange, into: Map.new, do: {{x,y}, s[{x,y}] - zs(s,x,y,g)}
  end

  defp zs(s, x, y, g) do
    if get(s,x,y) == 0 or                                       # P1
      (get(s,x-1,y) + get(s,x,y+1) + get(s,x+g,y-1+g)) == 3 or  # P2, P4, P6/P8
      (get(s,x-1+g,y+g) + get(s,x+1,y) + get(s,x,y-1)) == 3 do  # P4/P2, P6, P8
      0
    else
      next = for {i,j} <- @neighbours, do: get(s, x+i, y+j)
      bp1 = Enum.sum(next)                                      # B(P1)
      if bp1 in 2..6 do
        ap1 = (next++[hd(next)]) |> Enum.chunk(2,1) |> Enum.count(fn [a,b] -> a<b end)  # A(P1)
        if ap1 == 1, do: 1, else: 0
      else
        0
      end
    end
  end

  defp get(map, x, y), do: Map.get(map, {x,y}, 0)

  defp range(map), do: range(Map.keys(map), 0, 0)
  defp range([], xmax, ymax), do: {0 .. xmax, 0 .. ymax}
  defp range([{x,y} | t], xmax, ymax), do: range(t, max(x,xmax), max(y,ymax))

  @display  %{0 => " ", 1 => "#"}
  defp print(map, xrange, yrange) do
    Enum.each(xrange, fn x ->
      IO.puts (for y <- yrange, do: @display[map[{x,y}]])
    end)
  end
end

str = """
...........................................................
.#################...................#############.........
.##################...............################.........
.###################............##################.........
.########.....#######..........###################.........
...######.....#######.........#######.......######.........
...######.....#######........#######.......................
...#################.........#######.......................
...###############...........#######.......................
...#################.........#######.......................
...######....########........#######.......................
...######.....#######........#######.......................
...######.....#######.........#######.......######.........
.########.....#######..........###################.........
.########.....#######..#####....##################.######..
.########.....#######..#####......################.######..
.########.....#######..#####.........#############.######..
...........................................................
"""
ZhangSuen.thinning(str)

str = """
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
"""
ZhangSuen.thinning(str, ?1)


<hallway>
  <door number="1">closed</door>
  <door number="2">closed</door>
  <door number="3">closed</door>
  <door number="4">closed</door>
  ... etc ...
  <door number="100">closed</door>
<hallway>


# jq optimizes the recursive call of _gcd in the following:
def gcd(a;b):
  def _gcd:
    if .[1] != 0 then [.[1], .[0] % .[1]] | _gcd else .[0] end;
  [a,b] | _gcd ;

# emit the yellowstone sequence as a stream
def yellowstone:
  1,2,3,
  ({ a: [2, 3],                               # the last two items only
     b: {"1":  true, "2": true, "3" : true},  # a record, to avoid having to save the entire history
     start: 4 }
   | foreach range(1; infinite) as $n (.;
       first(
          .b as $b
     	  | .start = first( range(.start;infinite) | select($b[tostring]|not) )
          | foreach range(.start; infinite) as $i (.;
              .emit = null
              | ($i|tostring) as $is
              | if .b[$is] then .
              # "a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2)"
              elif (gcd($i; .a[1]) == 1) and (gcd($i; .a[0]) > 1)
              then .emit = $i
              | .a = [.a[1], $i]
              | .b[$is] = true
              else .
              end;
              select(.emit)) );
       .emit ));


using Plots

function yellowstone(N)
    a = [1, 2, 3]
    b = Dict(1 => 1, 2 => 1, 3 => 1)
    start = 4
    while length(a) < N
        inseries = true
        for i in start:typemax(Int)
            if haskey(b, i)
                if inseries
                    start += 1
                end
            else
                inseries = false
            end
            if !haskey(b, i) && (gcd(i, a[end]) == 1) && (gcd(i, a[end - 1]) > 1)
                push!(a, i)
                b[i] = 1
                break
            end
        end
    end
    return a
end

println("The first 30 entries of the Yellowstone permutation:\n", yellowstone(30))

x = 1:100
y = yellowstone(100)
plot(x, y)


fun main() {
    println("First 30 values in the yellowstone sequence:")
    println(yellowstoneSequence(30))
}

private fun yellowstoneSequence(sequenceCount: Int): List<Int> {
    val yellowstoneList = mutableListOf(1, 2, 3)
    var num = 4
    val notYellowstoneList = mutableListOf<Int>()
    var yellowSize = 3
    while (yellowSize < sequenceCount) {
        var found = -1
        for (index in notYellowstoneList.indices) {
            val test = notYellowstoneList[index]
            if (gcd(yellowstoneList[yellowSize - 2], test) > 1 && gcd(
                    yellowstoneList[yellowSize - 1], test
                ) == 1
            ) {
                found = index
                break
            }
        }
        if (found >= 0) {
            yellowstoneList.add(notYellowstoneList.removeAt(found))
            yellowSize++
        } else {
            while (true) {
                if (gcd(yellowstoneList[yellowSize - 2], num) > 1 && gcd(
                        yellowstoneList[yellowSize - 1], num
                    ) == 1
                ) {
                    yellowstoneList.add(num)
                    yellowSize++
                    num++
                    break
                }
                notYellowstoneList.add(num)
                num++
            }
        }
    }
    return yellowstoneList
}

private fun gcd(a: Int, b: Int): Int {
    return if (b == 0) {
        a
    } else gcd(b, a % b)
}


#!/usr/bin/txr -f
@(next :args)
@(cases)
@  QUERY
@  PAGE
@(or)
@  (throw error "specify query and page# (from zero)")
@(end)
@(next (open-command "!wget -O - http://search.yahoo.com/[email protected]\&[email protected]{PAGE}1 2> /dev/null"))
@(all)
@  (coll)]+/>@TITLE@(end)
@(and)
@  (coll)
@ABSTR
@(end)
@(end)
@(output)
@  (repeat)
TITLE: @TITLE
URL: @URL
TEXT: @ABSTR
---
@  (end)
@(end)


/* yahoo_search_interface.wren */

import "./pattern" for Pattern

class YahooSearch {
    construct new(url, title, desc) {
        _url = url
        _title = title
        _desc = desc
    }

    toString { "URL: %(_url)\nTitle: %(_title)\nDescription: %(_desc)\n" }
}

var CURLOPT_URL = 10002
var CURLOPT_FOLLOWLOCATION = 52
var CURLOPT_WRITEFUNCTION = 20011
var CURLOPT_WRITEDATA = 10001

foreign class Buffer {
    construct new() {}  // C will allocate buffer of a suitable size

    foreign value       // returns buffer contents as a string
}

foreign class Curl {
    construct easyInit() {}

    foreign easySetOpt(opt, param)

    foreign easyPerform()

    foreign easyCleanup()
}

var curl = Curl.easyInit()

var getContent = Fn.new { |url|
    var buffer = Buffer.new()
    curl.easySetOpt(CURLOPT_URL, url)
    curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1)
    curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0)  // write function to be supplied by C
    curl.easySetOpt(CURLOPT_WRITEDATA, buffer)
    curl.easyPerform()
    return buffer.value
}

var p1 = Pattern.new("class/=\" d-ib ls-05 fz-20 lh-26 td-hu tc va-bot mxw-100p\" href/=\"[+1^\"]\"")
var p2 = Pattern.new("class/=\" d-ib p-abs t-0 l-0 fz-14 lh-20 fc-obsidian wr-bw ls-n pb-4\">[+1^<]<")
var p3 = Pattern.new("<span class/=\" fc-falcon\">[+1^<]<")

var pageSize = 7
var totalCount = 0

var yahooSearch = Fn.new { |query, page|
    System.print("Page %(page):\n=======\n")
    var next = (page - 1) * pageSize + 1
    var url = "https://search.yahoo.com/search?fr=opensearch&pz=%(pageSize)&p=%(query)&b=%(next)"
    var content = getContent.call(url).replace("<b>", "").replace("</b>", "")
    var matches1 = p1.findAll(content)
    var count = matches1.count
    if (count == 0) return false
    var matches2 = p2.findAll(content)
    var matches3 = p3.findAll(content)
    totalCount = totalCount + count
    var ys = List.filled(count, null)
    for (i in 0...count) {
        var url   = matches1[i].capsText[0]
        var title = matches2[i].capsText[0]
        var desc  = matches3[i].capsText[0].replace("'", "'")
        ys[i] = YahooSearch.new(url, title, desc)
    }
    System.print(ys.join("\n"))
    return true
}

var page = 1
var limit = 2
var query = "rosettacode"
System.print("Searching for '%(query)' on Yahoo!\n")
while (page <= limit && yahooSearch.call(query, page)) {
    page = page + 1
    System.print()
}
System.print("Displayed %(limit) pages with a total of %(totalCount) entries.")
curl.easyCleanup()


declare
  %%            state          move   success     failure
  States = unit(right:        [ 1# 0  downLeft    downInstead]
                downInstead:  [ 0# 1  downLeft    terminate]
                downLeft:     [~1# 1  downLeft    down]
                down:         [ 0# 1  topRight    rightInstead]
                rightInstead: [ 1# 0  topRight    terminate]
                topRight:     [ 1#~1  topRight    right])

  fun {CreateZigZag N}
     ZZ = {Create2DTuple N N}

     %% recursively walk through 2D tuple and set values
     proc {Walk Pos=X#Y Count State}
        [Dir Success Failure] = States.State
        NextPos = {Record.zip Pos Dir Number.'+'}
        Valid = {Record.all NextPos fun {$ C} C > 0 andthen C =< N end}
        NewPos = if Valid then NextPos else Pos end
        NewCount = if Valid then Count + 1 else Count end
        NewState = if Valid then Success else Failure end
     in
        ZZ.Y.X = Count
        if NewState \= terminate then
           {Walk NewPos NewCount NewState}
        end
     end
  in
     {Walk 1#1 0 right}
     ZZ
  end

  fun {Create2DTuple W H}
     T = {MakeTuple unit H}
  in
     {Record.forAll T fun {$} {MakeTuple unit W} end}
     T
  end
in
  {Inspect {CreateZigZag 5}}


' version 08-10-2016
' compile with: fbc -s console

Data "00000000000000000000000000000000"
Data "01111111110000000111111110000000"
Data "01110001111000001111001111000000"
Data "01110000111000001110000111000000"
Data "01110001111000001110000000000000"
Data "01111111110000001110000000000000"
Data "01110111100000001110000111000000"
Data "01110011110011101111001111011100"
Data "01110001111011100111111110011100"
Data "00000000000000000000000000000000"
Data "END"

' ------=< MAIN >=------

Dim As UInteger x, y, m, n
Dim As String input_str

Do        ' find out how big it is
  Read input_str
  If input_str = "END" Then Exit Do
  If x < Len(input_str) Then x = Len(input_str)
  y = y + 1
Loop

m = x -1 : n = y -1
ReDim As UByte old(m, n), new_(m, n)

y = 0
Restore   ' restore data pointer
Do        ' put data in array
  Read input_str
  If input_str="END" Then Exit Do
  For x = 0 To Len(input_str) -1
    old(x,y) = input_str[x] - Asc("0")
    ' print image
    If old(x, y) = 0 Then Print "."; Else Print "#";
  Next
  Print
  y = y + 1
Loop

'corners and sides do not change
For x = 0 To m
  new_(x, 0) = old(x, 0)
  new_(x, n) = old(x, n)
Next

For y = 0 To n
  new_(0, y) = old(0, y)
  new_(m, y) = old(m, y)
Next

Dim As UInteger tmp, change, stage = 1
Do
  change = 0
  For y = 1 To n -1
    For x = 1 To m -1
      ' -1-
      If old(x,y) = 0 Then ' first condition, p1 must be black
        new_(x,y) = 0
        Continue For
      End If
      ' -2-
      tmp = old(x, y -1) + old(x +1, y -1)
      tmp = tmp + old(x +1, y) + old(x +1, y +1) + old(x, y +1)
      tmp = tmp + old(x -1, y +1) + old(x -1, y) + old(x -1, y -1)
      If tmp < 2 OrElse tmp > 6 Then ' 2 <= B(p1) <= 6
        new_(x, y) = 1
        Continue For
      End If
      ' -3-
      tmp = 0
      If old(x   , y   ) = 0 And old(x   , y -1) = 1 Then tmp += 1  ' p1 > p2
      If old(x   , y -1) = 0 And old(x +1, y -1) = 1 Then tmp += 1  ' p2 > p3
      If old(x +1, y -1) = 0 And old(x +1, y   ) = 1 Then tmp += 1  ' p3 > p4
      If old(x +1, y   ) = 0 And old(x +1, y +1) = 1 Then tmp += 1  ' p4 > p5
      If old(x +1, y +1) = 0 And old(x   , y +1) = 1 Then tmp += 1  ' p5 > p6
      If old(x   , y +1) = 0 And old(x -1, y +1) = 1 Then tmp += 1  ' p6 > p7
      If old(x -1, y +1) = 0 And old(x -1, y   ) = 1 Then tmp += 1  ' p7 > p8
      If old(x -1, y   ) = 0 And old(x -1, y -1) = 1 Then tmp += 1  ' p8 > p9
      If old(x -1, y -1) = 0 And old(x   , y -1) = 1 Then tmp += 1  ' p9 > p2
      ' tmp = 1 ==> A(P1) = 1
      If tmp <> 1 Then
        new_(x, y) = 1
        Continue For
      End If
      If (stage And 1) = 1 Then
        ' step 1 -4- -5-
        If (old(x, y -1) + old(x +1, y) + old(x, y +1)) = 3 OrElse _
           (old(x +1, y) + old(x, y +1) + old(x -1, y)) = 3 Then
          new_(x, y) = 1
          Continue For
        End If
      Else
        ' step 2 -4- -5-
        If (old(x, y -1) + old(x +1, y) + old(x -1, y)) = 3 OrElse _
           (old(x, y -1) + old(x, y +1) + old(x -1, y)) = 3 Then
          new_(x, y) = 1
          Continue For
        End If
      End If
      ' all condition are met, make p1 white (0)
      new_(x, y) = 0
      change = 1 ' flag change
    Next
  Next

  ' copy new_() into old()
  For y = 0 To n
    For x = 0 To m
      old(x, y) = new_(x, y)
    Next
  Next

  stage += 1
Loop Until change = 0 ' stop when there are no changes made

Print ' print result
Print "End result"
For y = 0 To n
  For x = 0 To m
    If old(x, y) = 0 Then Print "."; Else Print "#";
  Next
  Print
Next

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

<xsl:template match="/">
  <hallway>
    <xsl:for-each select="1 to 100">
      <xsl:variable name="door-num" select="position()" />
      <door number="{$door-num}">
        <xsl:value-of select="('closed','open')[
	    number( sum( for $pass in 1 to 100 return
	    number(($door-num mod $pass) = 0)) mod 2 = 1) + 1]" />
      </door>
    </xsl:for-each>
  </hallway>
</xsl:template>

</xsl:stylesheet>