Paste: some oldclay code

Author: pruned
Mode: text
Date: Wed, 23 Mar 2011 19:56:35
Plain Text |
import ranrot.*;

//
// System
// 

record System
(
    r: Pointer[RanrotBGen],
    n: Int,
    board: Vector[Int],
    rdiag: Vector[Int],
    ldiag: Vector[Int],
    E: Int,
);

overload System(n, r)
{
    var s = System();
    s.n = n;
    s.r = &r;

    resize(s.board, n);
    resize(s.rdiag, 2*n);
    resize(s.ldiag, 2*n);
    
    sample(s);
    
    return s;
}

sample(s: System)
{
    for(x in range(s.n))
        s.board[x] = x; // biased, valid initial board...
        
    // burn-in
    for (i in range(100))
    {
        var r1 = randomInt(s.r^, 0, s.n-1);
        var r2 = randomInt(s.r^, 0, s.n-1);
        swap(s.board[r1], s.board[r2]);
    }
        
    setDiags(s);
    s.E = computeEnergy(s);
}

var noRandom = true;

var cached = 0;
var cachedNum = 0;

fastRandomInt(r: RanrotBGen, min, max) Int
{
    if (true) return randomInt(r, min, max);
        
        cached += 101;
        if (cached>100000) cached = 0;
        
        return cached%max;
        
      /*  
    if (cached <= 0)
    {
        cachedNum = randomInt(r, min, 1024*1024*1024);
        cached = 400;
    }

    var r = cachedNum % max;
    cachedNum = cachedNum / max;
    cached -= 1;
    return r;
*/
    //if (noRandom) return 1;
    //return randomInt(r, min, max);
}

breakpoint() __llvm__
{
    call void asm sideeffect "int $$3", ""()
    ret i32 0
}

tryStep(s: System, f)
{

//if (true) return false;

    var r1 = fastRandomInt(s.r^, 0, s.n-1);
    var r2 = fastRandomInt(s.r^, 0, s.n-1);
  
    //var r1 = 1;
    //var r2 = 0;
  /*
    if (noRandom)
    {
        r1 = 0;
        r2 = 0;
    }*/
    
    //var oldE = s.E;
    //s.E = computeEnergy(s);
    
    //breakpoint();

    //if (true) return true;
/*    
    var newE = energyWithSwappedRows(s, r1, r2);

    if (f(newE))
    {
        s.E = newE;
        diagUpdateRemoveRow(s, r1);
        diagUpdateRemoveRow(s, r2);
        swap(s.board[r1], s.board[r2]);
        //for (x in [r1, r2]) energyUpdateAddRow(s, x);
        diagUpdateAddRow(s, r1);
        diagUpdateAddRow(s, r2);
//if(s.E != computeEnergy(s)) println("ouch !");
        //testDiags(s);
        return true;
    }
//if(s.E != computeEnergy(s)) println("ouch !");
//if(s.E != computeEnergy(s)) println("ouch !");
        //testDiags(s);
    return false;

//    */

    //for (x in [r1, r2]) energyUpdateRemoveRow(s, x);
    energyUpdateRemoveRow(s, r1);
    energyUpdateRemoveRow(s, r2);
    swap(s.board[r1], s.board[r2]);
    //for (x in [r1, r2]) energyUpdateAddRow(s, x);
    energyUpdateAddRow(s, r1);
    energyUpdateAddRow(s, r2);

    //if(s.E != computeEnergy(s)) println("ouch !");


    if (not f(s.E))
    //if (true)
    {
        // rejected: undo step
        //for (x in [r1, r2]) energyUpdateRemoveRow(s, x);
        energyUpdateRemoveRow(s, r1);
        energyUpdateRemoveRow(s, r2);
        swap(s.board[r1], s.board[r2]);
        //for (x in [r1, r2]) energyUpdateAddRow(s, x);
        energyUpdateAddRow(s, r1);
        energyUpdateAddRow(s, r2);

        //if(s.E != computeEnergy(s)) println("ouch2 !");
        
        //s.E = oldE;
        return false;
    }

    return true;
    // */
}

energyWithSwappedRows(s: System, r1, r2)
{

    var collision = false;

    var a = s.board[r1]-r1+s.n;
    var b = s.board[r2]-r2+s.n;
    var c = s.board[r2]-r1+s.n;
    var d = s.board[r1]-r2+s.n;

    //println([a,b,c,d]);

    if (a==b or a==c or a==d or b==c or b==d or c==d)
        collision = true;

    var a = s.board[r1]-r1+s.n;
    var b = s.board[r2]-r2+s.n;
    var c = s.board[r2]-r1+s.n;
    var d = s.board[r1]-r2+s.n;

    //println([a,b,c,d]);
    
    if (a==b or a==c or a==d or b==c or b==d or c==d)
        collision = true;

    //collision = false;

    if (collision)
    {
/*
    swap(s.board[r1], s.board[r2]);
    var newE = computeEnergy(s);
    swap(s.board[r1], s.board[r2]);
  */
  
    //var olds = s;
  
    energyUpdateRemoveRow(s, r1);
    energyUpdateRemoveRow(s, r2);
    swap(s.board[r1], s.board[r2]);
    energyUpdateAddRow(s, r1);
    energyUpdateAddRow(s, r2);

    var newE = s.E;
        
    energyUpdateRemoveRow(s, r1);
    energyUpdateRemoveRow(s, r2);
    swap(s.board[r1], s.board[r2]);
    energyUpdateAddRow(s, r1);
    energyUpdateAddRow(s, r2);
        
    //s = olds;
    
    return newE;    
    }

    //println("test");
    //testDiags(s);

    var newE = s.E;
    newE -= if (s.rdiag[s.board[r1]-r1+s.n] > 1) 1 else 0;
    newE -= if (s.ldiag[s.board[r1]+r1] > 1) 1 else 0;
    newE -= if (s.rdiag[s.board[r2]-r2+s.n] > 1) 1 else 0;
    newE -= if (s.ldiag[s.board[r2]+r2] > 1) 1 else 0;
/*
    // diags
    newE += if ((s.board[r2]-r2 == s.board[r1]-r1) s.rdiag[s.board[r2]-r2+s.n] == 2) 1 else 0;
    newE += if ((s.board[r2]+r2 == s.board[r1]+r1) s.ldiag[s.board[r2]+r2] == 2) 1 else 0;
*/

    //println(newE);

    newE += if (s.rdiag[s.board[r2]-r1+s.n] >= 1) 1 else 0;
    newE += if (s.ldiag[s.board[r2]+r1] >= 1) 1 else 0;
    newE += if (s.rdiag[s.board[r1]-r2+s.n] >= 1) 1 else 0;
    newE += if (s.ldiag[s.board[r1]+r2] >= 1) 1 else 0;
/*
    // diags
    newE -= if ((s.board[r2]-r2 == s.board[r1]-r1) s.rdiag[s.board[r2]-r2+s.n] == 2) 1 else 0;
    newE -= if ((s.board[r2]+r2 == s.board[r1]+r1) s.ldiag[s.board[r2]+r2] == 2) 1 else 0;
*/
/*
    swap(s.board[r1], s.board[r2]);
    var newE2 = computeEnergy(s);
    swap(s.board[r1], s.board[r2]);

    if (newE != newE2)
    {
        println([newE, newE2]);
        println([r1, r2]);
        print(s);
    swap(s.board[r1], s.board[r2]);
        print(s);
    swap(s.board[r1], s.board[r2]);
        breakpoint();
    }
*/
    return newE;

    // implement...

    //if (s.rdiag[s.board[x]-x+s.n] > 1) s.E -= 1;
    //s.E -= if (s.rdiag[s.board[x]-x+s.n] > 1) 1 else 0;
    //s.rdiag[s.board[x]-x+s.n] -= 1;
    
    //if (s.ldiag[s.board[x]+x] > 1) s.E -= 1;
    //s.E -= if (s.ldiag[s.board[x]+x] > 1) 1 else 0;
    //s.ldiag[s.board[x]+x] -= 1;
}

diagUpdateRemoveRow(s: System, x)
{
    s.rdiag[s.board[x]-x+s.n] -= 1;
    s.ldiag[s.board[x]+x] -= 1;
}

diagUpdateAddRow(s: System, x)
{
    s.rdiag[s.board[x]-x+s.n] += 1;
    s.ldiag[s.board[x]+x] += 1;
}

energyUpdateRemoveRow(s: System, x)
{
    //if (s.rdiag[s.board[x]-x+s.n] > 1) s.E -= 1;
    s.E -= if (s.rdiag[s.board[x]-x+s.n] > 1) 1 else 0;
    s.rdiag[s.board[x]-x+s.n] -= 1;
    
    //if (s.ldiag[s.board[x]+x] > 1) s.E -= 1;
    s.E -= if (s.ldiag[s.board[x]+x] > 1) 1 else 0;
    s.ldiag[s.board[x]+x] -= 1;
}

energyUpdateAddRow(s: System, x)
{
    s.rdiag[s.board[x]-x+s.n] += 1;
    //if (s.rdiag[s.board[x]-x+s.n] > 1) s.E += 1;
    s.E += if (s.rdiag[s.board[x]-x+s.n] > 1) 1 else 0;

    s.ldiag[s.board[x]+x] += 1;
    //if (s.ldiag[s.board[x]+x] > 1) s.E += 1;
    s.E += if (s.ldiag[s.board[x]+x] > 1) 1 else 0;
}

testDiags(s: System)
{
    var oldr = s.rdiag;
    var oldl = s.ldiag;

    for(v in s.rdiag) v = 0;
    for(v in s.ldiag) v = 0;
    
    for(x in range(s.n))
    {
        s.rdiag[s.board[x]-x+s.n] += 1;
        s.ldiag[s.board[x]+x] += 1;
    }

    for (x in range(size(oldr))) if (oldr[x] != s.rdiag[x]) println("rdiag corrupted");
    for (x in range(size(oldl))) if (oldl[x] != s.ldiag[x]) println("ldiag corrupted");

    // avoid side effect
    s.rdiag = oldr;
    s.ldiag = oldl;
}

setDiags(s: System)
{
    for(v in s.rdiag) v = 0;
    for(v in s.ldiag) v = 0;
    
    for(x in range(s.n))
    {
        s.rdiag[s.board[x]-x+s.n] += 1;
        s.ldiag[s.board[x]+x] += 1;
    }
}

computeEnergy(s: System)
{
    var oldr = s.rdiag;
    var oldl = s.ldiag;

    for(v in s.rdiag) v = 0;
    for(v in s.ldiag) v = 0;
    
    for(x in range(s.n))
    {
        s.rdiag[s.board[x]-x+s.n] += 1;
        s.ldiag[s.board[x]+x] += 1;
    }

    //for (x in range(size(oldr))) if (oldr[x] != s.rdiag[x]) println("rdiag corrupted");
    //for (x in range(size(oldl))) if (oldl[x] != s.ldiag[x]) println("ldiag corrupted");
    
    var E = 0;
    for (v in s.rdiag) E += max(v-1,0);
    for (v in s.ldiag) E += max(v-1,0);

    // avoid side effect
    s.rdiag = oldr;
    s.ldiag = oldl;

    return E;
}

overload print(s: System)
{
    println("board:");
    for (v in s.board) 
    {
        //println(v);
        for (x in range(v)) print(". ");
        print("x ");
        for (x in range(s.n-v-1)) print(". ");
        println();
    }
    //println("energy: ", s.E, "[", computeEnergy(s), "]");
    println("energy: ", computeEnergy(s));
}


























Annotation: alt syntax

Author: pruned
Mode: text
Date: Wed, 23 Mar 2011 21:35:25
Plain Text |
import ranrot.*;

//
// System
// 

record System
(
    Pointer[RanrotBGen] r,
    Int n,
    Vector[Int] board,
    Vector[Int] rdiag,
    Vector[Int] ldiag,
    Int e,
);

System: n, r
[
    var s = System: ;
    s.n = n;
    s.r = &r;

    s.board resize: n;
    s.rdiag resize: 2*n;
    s.ldiag resize: 2*n;
    
    sample: s;
    
    return s;
]

sample: System s
{
    for (range: s.n) each:
        [ x -> s.board[x] = x; ]; // biased, valid initial board...
        
    // burn-in
    for: (range: 100) each:
    [ i ->
        var r1 = s.r^ randomInt: 0, s.n-1;
        var r2 = s.r^ randomInt: 0, s.n-1;
        swap: s.board[r1], s.board[r2];
    ]
        
    setDiags: s;
    s.e = computeEnergy: s;
}

setDiags: System s
[
    s.rdiag each: [ v -> v = 0; ];
    s.ldiag each: [ v -> v = 0; ];
    
    (range: s.n) each: 
    [ x ->
        s.rdiag[s.board[x]-x+s.n] += 1;
        s.ldiag[s.board[x]+x] += 1;
    ];
]

computeEnergy: System s
[
    var oldr = s.rdiag;
    var oldl = s.ldiag;

    s.rdiag each: [ v -> v = 0; ];
    s.ldiag each: [ v -> v = 0; ];

    (range: s.n) each: 
    [ x ->
        s.rdiag[s.board[x]-x+s.n] += 1;
        s.ldiag[s.board[x]+x] += 1;
    ];

    //(range: (size: oldr)) each: [ x ->  if: oldr[x] != s.rdiag[x] then: [ println: "rdiag corrupted" ]; ];
    //(range: (size: oldl)) each: [ x ->  if: oldl[x] != s.ldiag[x] then: [ println: "ldiag corrupted" ]; ];
    
    var e = 0;
    s.rdiag each: [ v -> e += max: v-1, 0; ];
    s.ldiag each: [ v -> e += max: v-1, 0; ];

    // avoid side effect
    s.rdiag = oldr;
    s.ldiag = oldl;

    return e;
]

print: System s
[
    println: "board:";
    for: s.board each: 
    [ v ->
        //println: v;
        for: (range: v) each: [ print: ". "; ];
        print: "x ";
        for: (range: s.n-v-1) each: [ print: ". "; ];
        println: ;
    ];
    //println: "energy: ", s.e, "[", (computeEnergy: s), "]";
    println: "energy: ", (computeEnergy: s);
];

Annotation: some other code (oldclay)

Author: pruned
Mode: text
Date: Wed, 23 Mar 2011 22:11:57
Plain Text |
//import win32 ( WIN32_FIND_DATAA, FindFirst )

import win32;
import libc;
import io.paths;

private printWithSprintf(stream, formatString, value) {
    var buf = Array[CChar, 100]();
    libc.sprintf(&buf[0], cstring(formatString), value);
    var n = libc.strlen(&buf[0]);
    var ptr = Pointer[Byte](&buf[0]);
    write(stream, ptr, SizeT(n));
}

private record FileDirectory[S] (
    path : S,
);

[T | String?(T)]
direntSequence(x:T) = FileDirectory[T](x);

[T | String?(T)]
overload iterator(x:FileDirectory[T]) = FileIterator(x.path);


private record FileIterator (
    handle : win32.HANDLE,
    queued? : Bool,
    findData : win32.WIN32_FIND_DATAA,
);

private record FileInfo (
    name : String,
    system? : Bool,
    directory? : Bool,
);

[T | String?(T)]
overload FileIterator(path:T) self:FileIterator {
    self.handle = win32.FindFirstFileA(cstring(path), &self.findData);
    self.queued? = true;
    return self;
}

overload destroy(x:FileIterator) {
    win32.FindClose(x.handle);
}

overload hasNext?(x:FileIterator) {
    if (not x.queued?) {
        x.queued? = true;
        
        var returnCode = win32.FindNextFileA(x.handle, &x.findData);
        return (returnCode != 0);
    }
    else
        return true;
}

testFlag(flags, flag) = bitwiseAnd(flags, flag) == flag;

overload next(x:FileIterator) {
    if (not x.queued?)
        hasNext?(x);
    x.queued? = false;
    return FileInfo(
        String(CStringRef(begin(x.findData.cFileName))),
        testFlag(x.findData.dwFileAttributes, win32.FILE_ATTRIBUTE_SYSTEM),
        testFlag(x.findData.dwFileAttributes, win32.FILE_ATTRIBUTE_DIRECTORY)
    );
}

overload subtract(a:Char, b:Char)
{  
    return Int(a)-Int(b);
}

hexToInt(string)
{
    var number = 0;
    for (char in string)
    {
        if (char >= '0' and char <= '9')
            number = number * 16 + (char - '0');
        else if (char >= 'A' and char <= 'F')
            number = number * 16 + (char - 'A' + 10);
        else return (false, 0);
    }
    return (true, number);
}



errorMsg(msg)
{
    println(msg);
    flush(stdin);
    var buff = Array[Byte,1]();
    read(stdin, begin(buff),1);
}

renameFile(a,b)
{
    win32.MoveFileA(cstring(a), cstring(b));
}

massren()
{
    var files = Vector[String]();
    var dir = FileDirectory("*");
    for (fi in dir)
    {
        if (not fi.system? and not fi.directory?
            and fi.name != "massren.exe"
            and fi.name != "massren.txt")
                push(files, fi.name);
    }
    
    sort(files);
    
    if (not io.paths.pathExists?("massren.txt"))
    {
        println("listing...");
        var configFile = File("massren.txt", CREATE);
        
        printWithSprintf(configFile, "massren file -- directory hash: %8.0X\n", hash(files));
        for (f in files)        
            printlnTo(configFile, f);
            
        println("done !");
    }
    else
    {
        var configFile = File("massren.txt", READ);
        var header = readLine(configFile);
//        print(header);
        var hashString = slicedFrom(trimmed(header), size("massren file -- directory hash: "));
        var ok, hash = ...unpack(hexToInt(hashString));
        if (ok and hash == prelude.hash(files))
        {
            println("testing...");
            
            var filesFrom = files;
            var filesTo = Vector[String]();
            for(nameFrom in files)
            {   
                push(filesTo, trim(readLine(configFile)));
            }    
            print(filesTo);        
            println("renaming (1/2)...");
            for(nameFrom, nameTo in zipped(filesFrom, filesTo))
            {
               // println(nameFrom, " -> " ,"massren_temp_"+nameFrom);
                renameFile(nameFrom, "massren_temp_"+nameFrom);
            }
            println("renaming (2/2)...");
            for(nameFrom, nameTo in zipped(filesFrom, filesTo))
            {
              //  println("massren_temp_"+nameFrom, " -> " ,nameTo);
                renameFile("massren_temp_"+nameFrom, nameTo);
            }
            println("done !");
        } else
        {
            errorMsg("directory hash mismatch !");
            
        }
    }
}

main()
{
    //printWithSprintf(stdout, "massren file -- directory hash: %0.8X\n", 1);
    massren();
}

Annotation: some other code (altclay)

Author: pruned
Mode: text
Date: Wed, 23 Mar 2011 22:12:34
Plain Text |
//import win32 ( WIN32_FIND_DATAA, FindFirst )

import win32;
import libc;
import io.paths;

Private stream printWithSprintf: formatString, value [
    var buf = Array[CChar, 100]: ;
    libc.sprintf: &buf[0], (cstring: formatString), value;
    var n = libc.strlen: &buf[0];
    var ptr = Pointer[Byte]: &buf[0];
    stream write: ptr, (SizeT: n);
];

Private record FileDirectory[S] (
    S path,
);


direntSequence('T x) [String?('T)] = [ FileDirectory['T]: x ];


iterator(FileDirectory['T] x) [String?(T)] = [ FileIterator: x.path ];


private: record FileIterator (
    win32.HANDLE handle,
    Bool queued?,
    win32.WIN32_FIND_DATAA findData,
);

private: record FileInfo (
    String name,
    Bool system?,
    Bool directory?,
);


FileIterator: 'T path [String?('T)] = FileIterator self [
    self.handle = win32.FindFirstFileA: (cstring: path), &self.findData;
    self.queued? = true;
    return self;
];

overload destroy: FileIterator x [
    win32.FindClose(x.handle);
];

overload hasNext?(x:FileIterator) [
    if: (not: x.queued?) then: [
        x.queued? = true;
        
        var returnCode = win32.FindNextFileA: x.handle, &x.findData;
        return (returnCode != 0);
    ]
    else:
        [ return true; ];
];

flags testFlag: flag = [ (flags bitwiseAnd: flag) == flag ];

next FileIterator x [
    if: (not: x.queued?)
        then: [ hasNext?: x; ]
    x.queued? = false;
    return FileInfo:
        String: (CStringRef: (begin: x.findData.cFileName)),
        (testFlag: x.findData.dwFileAttributes, win32.FILE_ATTRIBUTE_SYSTEM),
        (testFlag: x.findData.dwFileAttributes, win32.FILE_ATTRIBUTE_DIRECTORY)
    ;
];

subtract: Char a, Char b
[  
    return (Int: a)-(Int: b);
];

hexToInt: string
[
    var number = 0;
    for: string each:
    [ char ->
        if: (char >= '0' and: char <= '9')
        then: [ number = number * 16 + (char - '0'); ]
        else: [ 
            if: (char >= 'A' and char <= 'F')
            then [ number = number * 16 + (char - 'A' + 10); ]
            else: [ return (false, 0); ];
        ];
    ];
    return (true, number);
];

errorMsg: msg
[
    println: msg;
    flush: stdin;
    var buff = Array[Byte,1]: ;
    stdin read: (begin: buff), 1;
];

renameFile: a, b
[
    win32.MoveFileA: (cstring: a), (cstring: b);
];

massren:
[
    var files = Vector[String]: ;
    var dir = FileDirectory: "*";
    for: dir each:
    [ fi ->
        if (and: (not: fi.system?), (not fi.directory?),
            (fi.name != "massren.exe"),
            (and fi.name != "massren.txt"))
        then: [ files push: fi.name; ];
    ];
    
    sort: files;
    
    if: (not: (io.paths.pathExists?: "massren.txt"))
    then: [
        println: "listing...";
        var configFile = File: "massren.txt", CREATE;
        
        configFile printWithSprintf: "massren file -- directory hash: %8.0X\n", (hash: files);
        for: files each:
            [ f -> printlnTo: configFile, f; ];
            
        println: "done !";
    ]
    else:
    [
        var configFile = File: "massren.txt", READ;
        var header = readLine: configFile;
//        print: header;
        var hashString = slicedFrom: (trimmed: header), (size: "massren file -- directory hash: ");
        var ok, hash = ...unpack: (hexToInt: hashString);
        if: (ok and: hash == (prelude.hash: files))
        then: [
            println: "testing...";
            
            var filesFrom = files;
            var filesTo = Vector[String]: ;
            for: files each:
            [ nameFrom ->
                push(filesTo, trim(readLine(configFile)));
            ];   
            print: filesTo;
            println: "renaming (1/2)...";
            for: (zipped: filesFrom, filesTo) each:
            [ nameFrom, nameTo ->
               // println(nameFrom, " -> " ,"massren_temp_"+nameFrom);
                renameFile(nameFrom, "massren_temp_"+nameFrom);
            ];
            println: "renaming (2/2)...";
            for: (zipped: filesFrom, filesTo) each:
            [ nameFrom, nameTo ->
              //  println: "massren_temp_"+nameFrom, " -> " ,nameTo;
                renameFile: "massren_temp_"+nameFrom, nameTo;
            ];
            println: "done !";
        ] else: 
        [
            errorMsg("directory hash mismatch !");
            
        ];
    ];
];

main:
[
    //stdout printWithSprintf: "massren file -- directory hash: %0.8X\n", 1;
    massren: ;
];

New Annotation

Summary:
Author:
Mode:
Body: