Commit bb91a7e2 authored by Russ Cox's avatar Russ Cox

test/bench/shootout: delete

We don't use these for benchmarking anymore.
Now we have the go1 dir and the benchmarks subrepo.
Some have problematic copyright notices, so move out of main repo.

Preserved in golang.org/x/exp/shootout.

Fixes #12688.
Fixes #13584.

Change-Id: Ic0b71191ca1a286d33d7813aca94bab1617a1c82
Reviewed-on: https://go-review.googlesource.com/18320Reviewed-by: default avatarIan Lance Taylor <iant@golang.org>
parent 91ba9f45
......@@ -9,7 +9,6 @@ import (
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
......@@ -502,25 +501,12 @@ func (t *tester) registerTests() {
}
}
// Doc and shootout tests only run on builders.
// Doc tests only run on builders.
// They find problems approximately never.
if t.hasBash() && t.goos != "nacl" && t.goos != "android" && !t.iOS() && os.Getenv("GO_BUILDER_NAME") != "" {
t.registerTest("doc_progs", "../doc/progs", "time", "go", "run", "run.go")
t.registerTest("wiki", "../doc/articles/wiki", "./test.bash")
t.registerTest("codewalk", "../doc/codewalk", "time", "./run")
for _, name := range t.shootoutTests() {
if name == "spectralnorm" {
switch os.Getenv("GO_BUILDER_NAME") {
case "linux-arm-arm5", "linux-mips64-minux":
// Heavy on floating point and takes over 20 minutes with
// softfloat on arm5 builder and over 33 minutes on MIPS64
// builder with kernel FPU emulator.
// Disabled per Issue 12688.
continue
}
}
t.registerSeqTest("shootout:"+name, "../test/bench/shootout", "time", "./timing.sh", "-test", name)
}
}
if t.goos != "android" && !t.iOS() {
......@@ -994,18 +980,6 @@ func (t *tester) testDirTest(dt *distTest, shard, shards int) error {
return nil
}
func (t *tester) shootoutTests() []string {
sh, err := ioutil.ReadFile(filepath.Join(t.goroot, "test", "bench", "shootout", "timing.sh"))
if err != nil {
log.Fatal(err)
}
m := regexp.MustCompile(`(?m)^\s+run="([\w+ ]+)"\s*$`).FindSubmatch(sh)
if m == nil {
log.Fatal("failed to find run=\"...\" line in test/bench/shootout/timing.sh")
}
return strings.Fields(string(m[1]))
}
// mergeEnvLists merges the two environment lists such that
// variables with the same name in "in" replace those in "out".
// out may be mutated.
......
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
* based on C program by Kevin Carson
*/
package main
import (
"flag"
"fmt"
)
var n = flag.Int("n", 15, "depth")
type Node struct {
item int
left, right *Node
}
type Arena struct {
head *Node
}
var arena Arena
func (n *Node) free() {
if n.left != nil {
n.left.free()
}
if n.right != nil {
n.right.free()
}
n.left = arena.head
arena.head = n
}
func (a *Arena) New(item int, left, right *Node) *Node {
if a.head == nil {
nodes := make([]Node, 3<<uint(*n))
for i := 0; i < len(nodes)-1; i++ {
nodes[i].left = &nodes[i+1]
}
a.head = &nodes[0]
}
n := a.head
a.head = a.head.left
n.item = item
n.left = left
n.right = right
return n
}
func bottomUpTree(item, depth int) *Node {
if depth <= 0 {
return arena.New(item, nil, nil)
}
return arena.New(item, bottomUpTree(2*item-1, depth-1), bottomUpTree(2*item, depth-1))
}
func (n *Node) itemCheck() int {
if n.left == nil {
return n.item
}
return n.item + n.left.itemCheck() - n.right.itemCheck()
}
const minDepth = 4
func main() {
flag.Parse()
maxDepth := *n
if minDepth+2 > *n {
maxDepth = minDepth + 2
}
stretchDepth := maxDepth + 1
check := bottomUpTree(0, stretchDepth).itemCheck()
fmt.Printf("stretch tree of depth %d\t check: %d\n", stretchDepth, check)
longLivedTree := bottomUpTree(0, maxDepth)
for depth := minDepth; depth <= maxDepth; depth += 2 {
iterations := 1 << uint(maxDepth-depth+minDepth)
check = 0
for i := 1; i <= iterations; i++ {
t := bottomUpTree(i, depth)
check += t.itemCheck()
t.free()
t = bottomUpTree(-i, depth)
check += t.itemCheck()
t.free()
}
fmt.Printf("%d\t trees of depth %d\t check: %d\n", iterations*2, depth, check)
}
fmt.Printf("long lived tree of depth %d\t check: %d\n", maxDepth, longLivedTree.itemCheck())
}
stretch tree of depth 16 check: -1
65536 trees of depth 4 check: -65536
16384 trees of depth 6 check: -16384
4096 trees of depth 8 check: -4096
1024 trees of depth 10 check: -1024
256 trees of depth 12 check: -256
64 trees of depth 14 check: -64
long lived tree of depth 15 check: -1
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Shootout Benchmarks
http://shootout.alioth.debian.org/
contributed by Kevin Carson
compilation:
gcc -O3 -fomit-frame-pointer -funroll-loops -static binary-trees.c -lm
icc -O3 -ip -unroll -static binary-trees.c -lm
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct tn {
struct tn* left;
struct tn* right;
long item;
} treeNode;
treeNode* NewTreeNode(treeNode* left, treeNode* right, long item)
{
treeNode* new;
new = (treeNode*)malloc(sizeof(treeNode));
new->left = left;
new->right = right;
new->item = item;
return new;
} /* NewTreeNode() */
long ItemCheck(treeNode* tree)
{
if (tree->left == NULL)
return tree->item;
else
return tree->item + ItemCheck(tree->left) - ItemCheck(tree->right);
} /* ItemCheck() */
treeNode* BottomUpTree(long item, unsigned depth)
{
if (depth > 0)
return NewTreeNode
(
BottomUpTree(2 * item - 1, depth - 1),
BottomUpTree(2 * item, depth - 1),
item
);
else
return NewTreeNode(NULL, NULL, item);
} /* BottomUpTree() */
void DeleteTree(treeNode* tree)
{
if (tree->left != NULL)
{
DeleteTree(tree->left);
DeleteTree(tree->right);
}
free(tree);
} /* DeleteTree() */
int main(int argc, char* argv[])
{
unsigned N, depth, minDepth, maxDepth, stretchDepth;
treeNode *stretchTree, *longLivedTree, *tempTree;
N = atol(argv[1]);
minDepth = 4;
if ((minDepth + 2) > N)
maxDepth = minDepth + 2;
else
maxDepth = N;
stretchDepth = maxDepth + 1;
stretchTree = BottomUpTree(0, stretchDepth);
printf
(
"stretch tree of depth %u\t check: %li\n",
stretchDepth,
ItemCheck(stretchTree)
);
DeleteTree(stretchTree);
longLivedTree = BottomUpTree(0, maxDepth);
for (depth = minDepth; depth <= maxDepth; depth += 2)
{
long i, iterations, check;
iterations = pow(2, maxDepth - depth + minDepth);
check = 0;
for (i = 1; i <= iterations; i++)
{
tempTree = BottomUpTree(i, depth);
check += ItemCheck(tempTree);
DeleteTree(tempTree);
tempTree = BottomUpTree(-i, depth);
check += ItemCheck(tempTree);
DeleteTree(tempTree);
} /* for(i = 1...) */
printf
(
"%li\t trees of depth %u\t check: %li\n",
iterations * 2,
depth,
check
);
} /* for(depth = minDepth...) */
printf
(
"long lived tree of depth %u\t check: %li\n",
maxDepth,
ItemCheck(longLivedTree)
);
return 0;
} /* main() */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
* based on C program by Kevin Carson
*/
package main
import (
"flag"
"fmt"
)
var n = flag.Int("n", 15, "depth")
type Node struct {
item int
left, right *Node
}
func bottomUpTree(item, depth int) *Node {
if depth <= 0 {
return &Node{item: item}
}
return &Node{item, bottomUpTree(2*item-1, depth-1), bottomUpTree(2*item, depth-1)}
}
func (n *Node) itemCheck() int {
if n.left == nil {
return n.item
}
return n.item + n.left.itemCheck() - n.right.itemCheck()
}
const minDepth = 4
func main() {
flag.Parse()
maxDepth := *n
if minDepth+2 > *n {
maxDepth = minDepth + 2
}
stretchDepth := maxDepth + 1
check := bottomUpTree(0, stretchDepth).itemCheck()
fmt.Printf("stretch tree of depth %d\t check: %d\n", stretchDepth, check)
longLivedTree := bottomUpTree(0, maxDepth)
for depth := minDepth; depth <= maxDepth; depth += 2 {
iterations := 1 << uint(maxDepth-depth+minDepth)
check = 0
for i := 1; i <= iterations; i++ {
check += bottomUpTree(i, depth).itemCheck()
check += bottomUpTree(-i, depth).itemCheck()
}
fmt.Printf("%d\t trees of depth %d\t check: %d\n", iterations*2, depth, check)
}
fmt.Printf("long lived tree of depth %d\t check: %d\n", maxDepth, longLivedTree.itemCheck())
}
stretch tree of depth 16 check: -1
65536 trees of depth 4 check: -65536
16384 trees of depth 6 check: -16384
4096 trees of depth 8 check: -4096
1024 trees of depth 10 check: -1024
256 trees of depth 12 check: -256
64 trees of depth 14 check: -64
long lived tree of depth 15 check: -1
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
http://shootout.alioth.debian.org/
contributed by Michael Barker
based on a Java contribution by Luzius Meisser
convert to C by dualamd
*/
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
enum Colour
{
blue = 0,
red = 1,
yellow = 2,
Invalid = 3
};
const char* ColourName[] = {"blue", "red", "yellow"};
const int STACK_SIZE = 32*1024;
typedef unsigned int BOOL;
const BOOL TRUE = 1;
const BOOL FALSE = 0;
int CreatureID = 0;
enum Colour doCompliment(enum Colour c1, enum Colour c2)
{
switch (c1)
{
case blue:
switch (c2)
{
case blue:
return blue;
case red:
return yellow;
case yellow:
return red;
default:
goto errlb;
}
case red:
switch (c2)
{
case blue:
return yellow;
case red:
return red;
case yellow:
return blue;
default:
goto errlb;
}
case yellow:
switch (c2)
{
case blue:
return red;
case red:
return blue;
case yellow:
return yellow;
default:
goto errlb;
}
default:
break;
}
errlb:
printf("Invalid colour\n");
exit( 1 );
}
/* convert integer to number string: 1234 -> "one two three four" */
char* formatNumber(int n, char* outbuf)
{
int ochar = 0, ichar = 0;
int i;
char tmp[64];
const char* NUMBERS[] =
{
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"
};
ichar = sprintf(tmp, "%d", n);
for (i = 0; i < ichar; i++)
ochar += sprintf( outbuf + ochar, " %s", NUMBERS[ tmp[i] - '0' ] );
return outbuf;
}
struct MeetingPlace
{
pthread_mutex_t mutex;
int meetingsLeft;
struct Creature* firstCreature;
};
struct Creature
{
pthread_t ht;
pthread_attr_t stack_att;
struct MeetingPlace* place;
int count;
int sameCount;
enum Colour colour;
int id;
BOOL two_met;
BOOL sameid;
};
void MeetingPlace_Init(struct MeetingPlace* m, int meetings )
{
pthread_mutex_init( &m->mutex, 0 );
m->meetingsLeft = meetings;
m->firstCreature = 0;
}
BOOL Meet( struct Creature* cr)
{
BOOL retval = TRUE;
struct MeetingPlace* mp = cr->place;
pthread_mutex_lock( &(mp->mutex) );
if ( mp->meetingsLeft > 0 )
{
if ( mp->firstCreature == 0 )
{
cr->two_met = FALSE;
mp->firstCreature = cr;
}
else
{
struct Creature* first;
enum Colour newColour;
first = mp->firstCreature;
newColour = doCompliment( cr->colour, first->colour );
cr->sameid = cr->id == first->id;
cr->colour = newColour;
cr->two_met = TRUE;
first->sameid = cr->sameid;
first->colour = newColour;
first->two_met = TRUE;
mp->firstCreature = 0;
mp->meetingsLeft--;
}
}
else
retval = FALSE;
pthread_mutex_unlock( &(mp->mutex) );
return retval;
}
void* CreatureThreadRun(void* param)
{
struct Creature* cr = (struct Creature*)param;
while (TRUE)
{
if ( Meet(cr) )
{
while (cr->two_met == FALSE)
sched_yield();
if (cr->sameid)
cr->sameCount++;
cr->count++;
}
else
break;
}
return 0;
}
void Creature_Init( struct Creature *cr, struct MeetingPlace* place, enum Colour colour )
{
cr->place = place;
cr->count = cr->sameCount = 0;
cr->id = ++CreatureID;
cr->colour = colour;
cr->two_met = FALSE;
pthread_attr_init( &cr->stack_att );
pthread_attr_setstacksize( &cr->stack_att, STACK_SIZE );
pthread_create( &cr->ht, &cr->stack_att, &CreatureThreadRun, (void*)(cr) );
}
/* format meeting times of each creature to string */
char* Creature_getResult(struct Creature* cr, char* str)
{
char numstr[256];
formatNumber(cr->sameCount, numstr);
sprintf( str, "%u%s", cr->count, numstr );
return str;
}
void runGame( int n_meeting, int ncolor, const enum Colour* colours )
{
int i;
int total = 0;
char str[256];
struct MeetingPlace place;
struct Creature *creatures = (struct Creature*) calloc( ncolor, sizeof(struct Creature) );
MeetingPlace_Init( &place, n_meeting );
/* print initial color of each creature */
for (i = 0; i < ncolor; i++)
{
printf( "%s ", ColourName[ colours[i] ] );
Creature_Init( &(creatures[i]), &place, colours[i] );
}
printf("\n");
/* wait for them to meet */
for (i = 0; i < ncolor; i++)
pthread_join( creatures[i].ht, 0 );
/* print meeting times of each creature */
for (i = 0; i < ncolor; i++)
{
printf( "%s\n", Creature_getResult(&(creatures[i]), str) );
total += creatures[i].count;
}
/* print total meeting times, should equal n_meeting */
printf( "%s\n\n", formatNumber(total, str) );
/* cleaup & quit */
pthread_mutex_destroy( &place.mutex );
free( creatures );
}
void printColours( enum Colour c1, enum Colour c2 )
{
printf( "%s + %s -> %s\n",
ColourName[c1],
ColourName[c2],
ColourName[doCompliment(c1, c2)] );
}
void printColoursTable(void)
{
printColours(blue, blue);
printColours(blue, red);
printColours(blue, yellow);
printColours(red, blue);
printColours(red, red);
printColours(red, yellow);
printColours(yellow, blue);
printColours(yellow, red);
printColours(yellow, yellow);
}
int main(int argc, char** argv)
{
int n = (argc == 2) ? atoi(argv[1]) : 600;
printColoursTable();
printf("\n");
const enum Colour r1[] = { blue, red, yellow };
const enum Colour r2[] = { blue, red, yellow,
red, yellow, blue,
red, yellow, red, blue };
runGame( n, sizeof(r1) / sizeof(r1[0]), r1 );
runGame( n, sizeof(r2) / sizeof(r2[0]), r2 );
return 0;
}
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
*/
package main
import (
"flag"
"fmt"
"strconv"
)
const (
blue = iota
red
yellow
ncol
)
var complement = [...]int{
red | red<<2: red,
red | yellow<<2: blue,
red | blue<<2: yellow,
yellow | red<<2: blue,
yellow | yellow<<2: yellow,
yellow | blue<<2: red,
blue | red<<2: yellow,
blue | yellow<<2: red,
blue | blue<<2: blue,
}
var colname = [...]string{
blue: "blue",
red: "red",
yellow: "yellow",
}
// information about the current state of a creature.
type info struct {
colour int // creature's current colour.
name int // creature's name.
}
// exclusive access data-structure kept inside meetingplace.
// if mate is nil, it indicates there's no creature currently waiting;
// otherwise the creature's info is stored in info, and
// it is waiting to receive its mate's information on the mate channel.
type rendez struct {
n int // current number of encounters.
mate chan<- info // creature waiting when non-nil.
info info // info about creature waiting.
}
// result sent by each creature at the end of processing.
type result struct {
met int
same int
}
var n = 600
func main() {
flag.Parse()
if flag.NArg() > 0 {
n, _ = strconv.Atoi(flag.Arg(0))
}
for c0 := 0; c0 < ncol; c0++ {
for c1 := 0; c1 < ncol; c1++ {
fmt.Printf("%s + %s -> %s\n", colname[c0], colname[c1], colname[complement[c0|c1<<2]])
}
}
fmt.Print("\n")
pallmall([]int{blue, red, yellow})
pallmall([]int{blue, red, yellow, red, yellow, blue, red, yellow, red, blue})
}
func pallmall(cols []int) {
// invariant: meetingplace always contains a value unless a creature
// is currently dealing with it (whereupon it must put it back).
meetingplace := make(chan rendez, 1)
meetingplace <- rendez{n: 0}
ended := make(chan result)
msg := ""
for i, col := range cols {
go creature(info{col, i}, meetingplace, ended)
msg += " " + colname[col]
}
fmt.Println(msg)
tot := 0
// wait for all results
for range cols {
result := <-ended
tot += result.met
fmt.Printf("%v%v\n", result.met, spell(result.same, true))
}
fmt.Printf("%v\n\n", spell(tot, true))
}
// in this function, variables ending in 0 refer to the local creature,
// variables ending in 1 to the creature we've met.
func creature(info0 info, meetingplace chan rendez, ended chan result) {
c0 := make(chan info)
met := 0
same := 0
for {
var othername int
// get access to rendez data and decide what to do.
switch r := <-meetingplace; {
case r.n >= n:
// if no more meetings left, then send our result data and exit.
meetingplace <- rendez{n: r.n}
ended <- result{met, same}
return
case r.mate == nil:
// no creature waiting; wait for someone to meet us,
// get their info and send our info in reply.
meetingplace <- rendez{n: r.n, info: info0, mate: c0}
info1 := <-c0
othername = info1.name
info0.colour = complement[info0.colour|info1.colour<<2]
default:
// another creature is waiting for us with its info;
// increment meeting count,
// send them our info in reply.
r.n++
meetingplace <- rendez{n: r.n, mate: nil}
r.mate <- info0
othername = r.info.name
info0.colour = complement[info0.colour|r.info.colour<<2]
}
if othername == info0.name {
same++
}
met++
}
}
var digits = [...]string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}
func spell(n int, required bool) string {
if n == 0 && !required {
return ""
}
return spell(n/10, false) + " " + digits[n%10]
}
blue + blue -> blue
blue + red -> yellow
blue + yellow -> red
red + blue -> yellow
red + red -> red
red + yellow -> blue
yellow + blue -> red
yellow + red -> blue
yellow + yellow -> yellow
blue red yellow
400 zero
400 zero
400 zero
one two zero zero
blue red yellow red yellow blue red yellow red blue
120 zero
120 zero
120 zero
120 zero
120 zero
120 zero
120 zero
120 zero
120 zero
120 zero
one two zero zero
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*
* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
* Based on fannkuch.scala by Rex Kerr
*/
package main
import (
"flag"
"fmt"
"runtime"
)
var n = flag.Int("n", 7, "count")
var nCPU = flag.Int("ncpu", 4, "number of cpus")
type Job struct {
start []int
n int
}
type Found struct {
who *Kucher
k int
}
type Kucher struct {
perm []int
temp []int
flip []int
in chan Job
}
func NewKucher(length int) *Kucher {
return &Kucher{
perm: make([]int, length),
temp: make([]int, length),
flip: make([]int, length),
in: make(chan Job),
}
}
func (k *Kucher) permute(n int) bool {
i := 0
for ; i < n-1 && k.flip[i] == 0; i++ {
t := k.perm[0]
j := 0
for ; j <= i; j++ {
k.perm[j] = k.perm[j+1]
}
k.perm[j] = t
}
k.flip[i]--
for i > 0 {
i--
k.flip[i] = i
}
return k.flip[n-1] >= 0
}
func (k *Kucher) count() int {
K := 0
copy(k.temp, k.perm)
for k.temp[0] != 0 {
m := k.temp[0]
for i := 0; i < m; i++ {
k.temp[i], k.temp[m] = k.temp[m], k.temp[i]
m--
}
K++
}
return K
}
func (k *Kucher) Run(foreman chan<- Found) {
for job := range k.in {
verbose := 30
copy(k.perm, job.start)
for i, v := range k.perm {
if v != i {
verbose = 0
}
k.flip[i] = i
}
K := 0
for {
if verbose > 0 {
for _, p := range k.perm {
fmt.Print(p + 1)
}
fmt.Println()
verbose--
}
count := k.count()
if count > K {
K = count
}
if !k.permute(job.n) {
break
}
}
foreman <- Found{k, K}
}
}
type Fanner struct {
jobind int
jobsdone int
k int
jobs []Job
workers []*Kucher
in chan Found
result chan int
}
func NewFanner(jobs []Job, workers []*Kucher) *Fanner {
return &Fanner{
jobs: jobs, workers: workers,
in: make(chan Found),
result: make(chan int),
}
}
func (f *Fanner) Run(N int) {
for msg := range f.in {
if msg.k > f.k {
f.k = msg.k
}
if msg.k >= 0 {
f.jobsdone++
}
if f.jobind < len(f.jobs) {
msg.who.in <- f.jobs[f.jobind]
f.jobind++
} else if f.jobsdone == len(f.jobs) {
f.result <- f.k
return
}
}
}
func swapped(a []int, i, j int) []int {
b := make([]int, len(a))
copy(b, a)
b[i], b[j] = a[j], a[i]
return b
}
func main() {
flag.Parse()
runtime.GOMAXPROCS(*nCPU)
N := *n
base := make([]int, N)
for i := range base {
base[i] = i
}
njobs := 1
if N > 8 {
njobs += (N*(N-1))/2 - 28 // njobs = 1 + sum(8..N-1) = 1 + sum(1..N-1) - sum(1..7)
}
jobs := make([]Job, njobs)
jobsind := 0
firstN := N
if firstN > 8 {
firstN = 8
}
jobs[jobsind] = Job{base, firstN}
jobsind++
for i := N - 1; i >= 8; i-- {
for j := 0; j < i; j++ {
jobs[jobsind] = Job{swapped(base, i, j), i}
jobsind++
}
}
nworkers := *nCPU
if njobs < nworkers {
nworkers = njobs
}
workers := make([]*Kucher, nworkers)
foreman := NewFanner(jobs, workers)
go foreman.Run(N)
for i := range workers {
k := NewKucher(N)
workers[i] = k
go k.Run(foreman.in)
foreman.in <- Found{k, -1}
}
fmt.Printf("Pfannkuchen(%d) = %d\n", N, <-foreman.result)
}
1234567
2134567
2314567
3214567
3124567
1324567
2341567
3241567
3421567
4321567
4231567
2431567
3412567
4312567
4132567
1432567
1342567
3142567
4123567
1423567
1243567
2143567
2413567
4213567
2345167
3245167
3425167
4325167
4235167
2435167
Pfannkuchen(7) = 16
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*
* The Computer Language Shootout
* http://shootout.alioth.debian.org/
* Contributed by Heiner Marxen
*
* "fannkuch" for C gcc
*
* $Id: fannkuch.1.gcc.code,v 1.15 2009-04-28 15:39:31 igouy-guest Exp $
*/
#include <stdio.h>
#include <stdlib.h>
#define Int int
#define Aint int
static long
fannkuch( int n )
{
Aint* perm;
Aint* perm1;
Aint* count;
long flips;
long flipsMax;
Int r;
Int i;
Int k;
Int didpr;
const Int n1 = n - 1;
if( n < 1 ) return 0;
perm = calloc(n, sizeof(*perm ));
perm1 = calloc(n, sizeof(*perm1));
count = calloc(n, sizeof(*count));
for( i=0 ; i<n ; ++i ) perm1[i] = i; /* initial (trivial) permu */
r = n; didpr = 0; flipsMax = 0;
for(;;) {
if( didpr < 30 ) {
for( i=0 ; i<n ; ++i ) printf("%d", (int)(1+perm1[i]));
printf("\n");
++didpr;
}
for( ; r!=1 ; --r ) {
count[r-1] = r;
}
#define XCH(x,y) { Aint t_mp; t_mp=(x); (x)=(y); (y)=t_mp; }
if( ! (perm1[0]==0 || perm1[n1]==n1) ) {
flips = 0;
for( i=1 ; i<n ; ++i ) { /* perm = perm1 */
perm[i] = perm1[i];
}
k = perm1[0]; /* cache perm[0] in k */
do { /* k!=0 ==> k>0 */
Int j;
for( i=1, j=k-1 ; i<j ; ++i, --j ) {
XCH(perm[i], perm[j])
}
++flips;
/*
* Now exchange k (caching perm[0]) and perm[k]... with care!
* XCH(k, perm[k]) does NOT work!
*/
j=perm[k]; perm[k]=k ; k=j;
}while( k );
if( flipsMax < flips ) {
flipsMax = flips;
}
}
for(;;) {
if( r == n ) {
return flipsMax;
}
/* rotate down perm[0..r] by one */
{
Int perm0 = perm1[0];
i = 0;
while( i < r ) {
k = i+1;
perm1[i] = perm1[k];
i = k;
}
perm1[r] = perm0;
}
if( (count[r] -= 1) > 0 ) {
break;
}
++r;
}
}
}
int
main( int argc, char* argv[] )
{
int n = (argc>1) ? atoi(argv[1]) : 0;
printf("Pfannkuchen(%d) = %ld\n", n, fannkuch(n));
return 0;
}
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*
* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
* Based on fannkuch.c by Heiner Marxen
*/
package main
import (
"flag"
"fmt"
)
var n = flag.Int("n", 7, "count")
func fannkuch(n int) int {
if n < 1 {
return 0
}
n1 := n - 1
perm := make([]int, n)
perm1 := make([]int, n)
count := make([]int, n)
for i := 0; i < n; i++ {
perm1[i] = i // initial (trivial) permutation
}
r := n
didpr := 0
flipsMax := 0
for {
if didpr < 30 {
for i := 0; i < n; i++ {
fmt.Printf("%d", 1+perm1[i])
}
fmt.Printf("\n")
didpr++
}
for ; r != 1; r-- {
count[r-1] = r
}
if perm1[0] != 0 && perm1[n1] != n1 {
flips := 0
for i := 1; i < n; i++ { // perm = perm1
perm[i] = perm1[i]
}
k := perm1[0] // cache perm[0] in k
for { // k!=0 ==> k>0
for i, j := 1, k-1; i < j; i, j = i+1, j-1 {
perm[i], perm[j] = perm[j], perm[i]
}
flips++
// Now exchange k (caching perm[0]) and perm[k]... with care!
j := perm[k]
perm[k] = k
k = j
if k == 0 {
break
}
}
if flipsMax < flips {
flipsMax = flips
}
}
for ; r < n; r++ {
// rotate down perm[0..r] by one
perm0 := perm1[0]
for i := 0; i < r; i++ {
perm1[i] = perm1[i+1]
}
perm1[r] = perm0
count[r]--
if count[r] > 0 {
break
}
}
if r == n {
return flipsMax
}
}
return 0
}
func main() {
flag.Parse()
fmt.Printf("Pfannkuchen(%d) = %d\n", *n, fannkuch(*n))
}
1234567
2134567
2314567
3214567
3124567
1324567
2341567
3241567
3421567
4321567
4231567
2431567
3412567
4312567
4132567
1432567
1342567
3142567
4123567
1423567
1243567
2143567
2413567
4213567
2345167
3245167
3425167
4325167
4235167
2435167
Pfannkuchen(7) = 16
This diff is collapsed.
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*
* http://shootout.alioth.debian.org/u32/program.php?test=fasta&lang=gcc&id=3
*/
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by Petr Prokhorenkov
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef fwrite_unlocked
// not available on OS X
#define fwrite_unlocked fwrite
#define fputc_unlocked fputc
#define fputs_unlocked fputs
#endif
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
#define unlikely(x) __builtin_expect((x), 0)
#define IM 139968
#define IA 3877
#define IC 29573
#define LINE_LEN 60
#define LOOKUP_SIZE 4096
#define LOOKUP_SCALE ((float)(LOOKUP_SIZE - 1))
typedef unsigned random_t;
void
random_init(random_t *random) {
*random = 42;
}
// Special version with result rescaled to LOOKUP_SCALE.
static inline
float
random_next_lookup(random_t *random) {
*random = (*random*IA + IC)%IM;
return (*random)*(LOOKUP_SCALE/IM);
}
struct amino_acid {
char sym;
float prob;
float cprob_lookup;
};
void
repeat(const char *alu, const char *title, int n) {
int len = strlen(alu);
char buffer[len + LINE_LEN];
int pos = 0;
memcpy(buffer, alu, len);
memcpy(buffer + len, alu, LINE_LEN);
fputs_unlocked(title, stdout);
while (n > 0) {
int bytes = n > LINE_LEN ? LINE_LEN : n;
fwrite_unlocked(buffer + pos, bytes, 1, stdout);
pos += bytes;
if (pos > len) {
pos -= len;
}
fputc_unlocked('\n', stdout);
n -= bytes;
}
}
/*
* Lookup table contains mapping from real values to cumulative
* probabilities. Careful selection of table size allows lookup
* virtually in constant time.
*
* All cumulative probabilities are rescaled to LOOKUP_SCALE,
* this allows to save one multiplication operation on each iteration
* in randomize().
*/
void *
fill_lookup(struct amino_acid **lookup, struct amino_acid *amino_acid, int amino_acid_size) {
float p = 0;
int i, j;
for (i = 0; i < amino_acid_size; i++) {
p += amino_acid[i].prob;
amino_acid[i].cprob_lookup = p*LOOKUP_SCALE;
}
// Prevent rounding error.
amino_acid[amino_acid_size - 1].cprob_lookup = LOOKUP_SIZE - 1;
for (i = 0, j = 0; i < LOOKUP_SIZE; i++) {
while (amino_acid[j].cprob_lookup < i) {
j++;
}
lookup[i] = &amino_acid[j];
}
return 0;
}
void
randomize(struct amino_acid *amino_acid, int amino_acid_size,
const char *title, int n, random_t *rand) {
struct amino_acid *lookup[LOOKUP_SIZE];
char line_buffer[LINE_LEN + 1];
int i, j;
line_buffer[LINE_LEN] = '\n';
fill_lookup(lookup, amino_acid, amino_acid_size);
fputs_unlocked(title, stdout);
for (i = 0, j = 0; i < n; i++, j++) {
if (j == LINE_LEN) {
fwrite_unlocked(line_buffer, LINE_LEN + 1, 1, stdout);
j = 0;
}
float r = random_next_lookup(rand);
struct amino_acid *u = lookup[(short)r];
while (unlikely(u->cprob_lookup < r)) {
++u;
}
line_buffer[j] = u->sym;
}
line_buffer[j] = '\n';
fwrite_unlocked(line_buffer, j + 1, 1, stdout);
}
struct amino_acid amino_acid[] = {
{ 'a', 0.27 },
{ 'c', 0.12 },
{ 'g', 0.12 },
{ 't', 0.27 },
{ 'B', 0.02 },
{ 'D', 0.02 },
{ 'H', 0.02 },
{ 'K', 0.02 },
{ 'M', 0.02 },
{ 'N', 0.02 },
{ 'R', 0.02 },
{ 'S', 0.02 },
{ 'V', 0.02 },
{ 'W', 0.02 },
{ 'Y', 0.02 },
};
struct amino_acid homo_sapiens[] = {
{ 'a', 0.3029549426680 },
{ 'c', 0.1979883004921 },
{ 'g', 0.1975473066391 },
{ 't', 0.3015094502008 },
};
static const char alu[] =
"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTG"
"GGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGA"
"GACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAA"
"AATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT"
"CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAAC"
"CCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTG"
"CACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
int
main(int argc, const char **argv) {
int n = argc > 1 ? atoi( argv[1] ) : 512;
random_t rand;
random_init(&rand);
repeat(alu, ">ONE Homo sapiens alu\n", n*2);
randomize(amino_acid, ARRAY_SIZE(amino_acid),
">TWO IUB ambiguity codes\n", n*3, &rand);
randomize(homo_sapiens, ARRAY_SIZE(homo_sapiens),
">THREE Homo sapiens frequency\n", n*5, &rand);
return 0;
}
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
* Based on C program by by Petr Prokhorenkov.
*/
package main
import (
"flag"
"os"
)
var out = make(buffer, 0, 32768)
var n = flag.Int("n", 1000, "length of result")
const Line = 60
func Repeat(alu []byte, n int) {
buf := append(alu, alu...)
off := 0
for n > 0 {
m := n
if m > Line {
m = Line
}
buf1 := out.NextWrite(m + 1)
copy(buf1, buf[off:])
buf1[m] = '\n'
if off += m; off >= len(alu) {
off -= len(alu)
}
n -= m
}
}
const (
IM = 139968
IA = 3877
IC = 29573
LookupSize = 4096
LookupScale float64 = LookupSize - 1
)
var rand uint32 = 42
type Acid struct {
sym byte
prob float64
cprob float64
next *Acid
}
func computeLookup(acid []Acid) *[LookupSize]*Acid {
var lookup [LookupSize]*Acid
var p float64
for i := range acid {
p += acid[i].prob
acid[i].cprob = p * LookupScale
if i > 0 {
acid[i-1].next = &acid[i]
}
}
acid[len(acid)-1].cprob = 1.0 * LookupScale
j := 0
for i := range lookup {
for acid[j].cprob < float64(i) {
j++
}
lookup[i] = &acid[j]
}
return &lookup
}
func Random(acid []Acid, n int) {
lookup := computeLookup(acid)
for n > 0 {
m := n
if m > Line {
m = Line
}
buf := out.NextWrite(m + 1)
f := LookupScale / IM
myrand := rand
for i := 0; i < m; i++ {
myrand = (myrand*IA + IC) % IM
r := float64(int(myrand)) * f
a := lookup[int(r)]
for a.cprob < r {
a = a.next
}
buf[i] = a.sym
}
rand = myrand
buf[m] = '\n'
n -= m
}
}
func main() {
defer out.Flush()
flag.Parse()
iub := []Acid{
{prob: 0.27, sym: 'a'},
{prob: 0.12, sym: 'c'},
{prob: 0.12, sym: 'g'},
{prob: 0.27, sym: 't'},
{prob: 0.02, sym: 'B'},
{prob: 0.02, sym: 'D'},
{prob: 0.02, sym: 'H'},
{prob: 0.02, sym: 'K'},
{prob: 0.02, sym: 'M'},
{prob: 0.02, sym: 'N'},
{prob: 0.02, sym: 'R'},
{prob: 0.02, sym: 'S'},
{prob: 0.02, sym: 'V'},
{prob: 0.02, sym: 'W'},
{prob: 0.02, sym: 'Y'},
}
homosapiens := []Acid{
{prob: 0.3029549426680, sym: 'a'},
{prob: 0.1979883004921, sym: 'c'},
{prob: 0.1975473066391, sym: 'g'},
{prob: 0.3015094502008, sym: 't'},
}
alu := []byte(
"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" +
"GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" +
"CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" +
"ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" +
"GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" +
"AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" +
"AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA")
out.WriteString(">ONE Homo sapiens alu\n")
Repeat(alu, 2**n)
out.WriteString(">TWO IUB ambiguity codes\n")
Random(iub, 3**n)
out.WriteString(">THREE Homo sapiens frequency\n")
Random(homosapiens, 5**n)
}
type buffer []byte
func (b *buffer) Flush() {
p := *b
if len(p) > 0 {
os.Stdout.Write(p)
}
*b = p[0:0]
}
func (b *buffer) WriteString(s string) {
p := b.NextWrite(len(s))
copy(p, s)
}
func (b *buffer) NextWrite(n int) []byte {
p := *b
if len(p)+n > cap(p) {
b.Flush()
p = *b
}
out := p[len(p) : len(p)+n]
*b = p[:len(p)+n]
return out
}
This diff is collapsed.
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
*/
package main
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"runtime"
"sort"
)
func count(data string, n int) map[string]int {
counts := make(map[string]int)
top := len(data) - n
for i := 0; i <= top; i++ {
s := data[i : i+n]
counts[s]++
}
return counts
}
func countOne(data string, s string) int {
return count(data, len(s))[s]
}
type kNuc struct {
name string
count int
}
type kNucArray []kNuc
func (kn kNucArray) Len() int { return len(kn) }
func (kn kNucArray) Swap(i, j int) { kn[i], kn[j] = kn[j], kn[i] }
func (kn kNucArray) Less(i, j int) bool {
if kn[i].count == kn[j].count {
return kn[i].name > kn[j].name // sort down
}
return kn[i].count > kn[j].count
}
func sortedArray(m map[string]int) kNucArray {
kn := make(kNucArray, len(m))
i := 0
for k, v := range m {
kn[i] = kNuc{k, v}
i++
}
sort.Sort(kn)
return kn
}
func printKnucs(a kNucArray) {
sum := 0
for _, kn := range a {
sum += kn.count
}
for _, kn := range a {
fmt.Printf("%s %.3f\n", kn.name, 100*float64(kn.count)/float64(sum))
}
fmt.Print("\n")
}
func main() {
runtime.GOMAXPROCS(4)
in := bufio.NewReader(os.Stdin)
three := []byte(">THREE ")
for {
line, err := in.ReadSlice('\n')
if err != nil {
fmt.Fprintln(os.Stderr, "ReadLine err:", err)
os.Exit(2)
}
if line[0] == '>' && bytes.Equal(line[0:len(three)], three) {
break
}
}
data, err := ioutil.ReadAll(in)
if err != nil {
fmt.Fprintln(os.Stderr, "ReadAll err:", err)
os.Exit(2)
}
// delete the newlines and convert to upper case
j := 0
for i := 0; i < len(data); i++ {
if data[i] != '\n' {
data[j] = data[i] &^ ' ' // upper case
j++
}
}
str := string(data[0:j])
var arr1, arr2 kNucArray
countsdone := make(chan bool)
go func() {
arr1 = sortedArray(count(str, 1))
countsdone <- true
}()
go func() {
arr2 = sortedArray(count(str, 2))
countsdone <- true
}()
interests := []string{"GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT"}
results := make([]chan string, len(interests))
for i, s := range interests {
ch := make(chan string)
results[i] = ch
go func(result chan string, ss string) {
result <- fmt.Sprintf("%d %s\n", countOne(str, ss), ss)
}(ch, s)
}
<-countsdone
<-countsdone
printKnucs(arr1)
printKnucs(arr2)
for _, rc := range results {
fmt.Print(<-rc)
}
}
T 31.520
A 29.600
C 19.480
G 19.400
AT 9.922
TT 9.602
TA 9.402
AA 8.402
GA 6.321
TC 6.301
TG 6.201
GT 6.041
CT 5.961
AG 5.841
CA 5.461
AC 5.441
CC 4.041
CG 4.021
GC 3.701
GG 3.341
54 GGT
24 GGTA
4 GGTATT
0 GGTATTTTAATT
0 GGTATTTTAATTTATAGT
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <glib.h>
typedef struct stat_s stat_t;
struct stat_s
{
const gchar *key;
long stat;
};
#define MAX_ELM (8192 / sizeof (stat_t))
static int
generate_frequencies (int fl, char *buffer, long buflen,
GHashTable *ht, GTrashStack **ts, GPtrArray *roots, GStringChunk *sc)
{
gchar *key;
long i;
if (fl > buflen) return 0;
if (fl == 0) return 0;
for (i = 0; i < buflen - fl + 1; ++i)
{
char nulled;
stat_t *stat;
nulled = buffer[i + fl];
buffer[i + fl] = '\0';
key = g_string_chunk_insert_const(sc, buffer + i);
stat = g_hash_table_lookup(ht, key);
if (!stat)
{
stat = g_trash_stack_pop(ts);
if (!stat)
{
int j;
stat = malloc(sizeof (stat_t) * MAX_ELM);
g_ptr_array_add(roots, stat);
for (j = 1; j < MAX_ELM; ++j)
g_trash_stack_push(ts, stat + j);
}
stat->stat = 1;
stat->key = key;
g_hash_table_insert(ht, key, stat);
}
else
stat->stat++;
buffer[i + fl] = nulled;
}
return buflen - fl + 1;
}
static int
cmp_func(gconstpointer a, gconstpointer b)
{
const stat_t *left = a;
const stat_t *right = b;
return right->stat - left->stat;
}
static void
sorted_list(gpointer key, gpointer value, gpointer user_data)
{
stat_t *data = value;
GList **lst = user_data;
*lst = g_list_insert_sorted(*lst, data, cmp_func);
}
static void
display_stat(gpointer data, gpointer user_data)
{
long *total = user_data;
stat_t *st = data;
printf("%s %.3f\n", st->key, 100 * (float) st->stat / *total);
}
void
write_frequencies (int fl, char *buffer, long buflen, GTrashStack **ts, GPtrArray *roots)
{
GStringChunk *sc;
GHashTable *ht;
GList *lst;
long total;
ht = g_hash_table_new_full(g_str_hash, g_str_equal, NULL /* free key */, NULL /* free value */);
sc = g_string_chunk_new(buflen);
lst = NULL;
total = generate_frequencies (fl, buffer, buflen, ht, ts, roots, sc);
if (!total) goto on_error;
g_hash_table_foreach(ht, sorted_list, &lst);
g_list_foreach(lst, display_stat, &total);
g_list_free(lst);
on_error:
g_hash_table_destroy(ht);
g_string_chunk_free(sc);
}
void
write_count (char *searchFor, char *buffer, long buflen, GTrashStack **ts, GPtrArray *roots)
{
GStringChunk *sc;
GHashTable *ht;
stat_t *result;
GList *lst;
long total;
long fl;
fl = strlen(searchFor);
ht = g_hash_table_new_full(g_str_hash, g_str_equal, NULL /* free key */, NULL /* free value */);
sc = g_string_chunk_new(buflen);
lst = NULL;
result = NULL;
total = generate_frequencies (fl, buffer, buflen, ht, ts, roots, sc);
if (!total) goto on_error;
result = g_hash_table_lookup(ht, searchFor);
on_error:
printf("%ld\t%s\n", result ? result->stat : 0, searchFor);
g_hash_table_destroy(ht);
g_string_chunk_free(sc);
}
int
main ()
{
char buffer[4096];
GTrashStack *ts;
GPtrArray *roots;
GString *stuff;
gchar *s;
int len;
roots = g_ptr_array_new();
ts = NULL;
while (fgets(buffer, sizeof (buffer), stdin))
if (strncmp(buffer, ">THREE", 6) == 0)
break;
stuff = g_string_new(NULL);
while (fgets(buffer, sizeof (buffer), stdin))
{
size_t sz;
if (buffer[0] == '>')
break;
sz = strlen(buffer);
if (buffer[sz - 1] == '\n')
--sz;
stuff = g_string_append_len(stuff, buffer, sz);
}
stuff = g_string_ascii_up(stuff);
len = stuff->len;
s = g_string_free(stuff, FALSE);
write_frequencies(1, s, len, &ts, roots);
printf("\n");
write_frequencies(2, s, len, &ts, roots);
printf("\n");
write_count("GGT", s, len, &ts, roots);
write_count("GGTA", s, len, &ts, roots);
write_count("GGTATT", s, len, &ts, roots);
write_count("GGTATTTTAATT", s, len, &ts, roots);
write_count("GGTATTTTAATTTATAGT", s, len, &ts, roots);
free(s);
g_ptr_array_foreach(roots, (GFunc)free, NULL);
g_ptr_array_free(roots, TRUE);
return 0;
}
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
*/
package main
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"sort"
)
var in *bufio.Reader
func count(data string, n int) map[string]int {
counts := make(map[string]int)
top := len(data) - n
for i := 0; i <= top; i++ {
s := data[i : i+n]
counts[s]++
}
return counts
}
func countOne(data string, s string) int {
return count(data, len(s))[s]
}
type kNuc struct {
name string
count int
}
type kNucArray []kNuc
func (kn kNucArray) Len() int { return len(kn) }
func (kn kNucArray) Swap(i, j int) { kn[i], kn[j] = kn[j], kn[i] }
func (kn kNucArray) Less(i, j int) bool {
if kn[i].count == kn[j].count {
return kn[i].name > kn[j].name // sort down
}
return kn[i].count > kn[j].count
}
func sortedArray(m map[string]int) kNucArray {
kn := make(kNucArray, len(m))
i := 0
for k, v := range m {
kn[i].name = k
kn[i].count = v
i++
}
sort.Sort(kn)
return kn
}
func print(m map[string]int) {
a := sortedArray(m)
sum := 0
for _, kn := range a {
sum += kn.count
}
for _, kn := range a {
fmt.Printf("%s %.3f\n", kn.name, 100*float64(kn.count)/float64(sum))
}
}
func main() {
in = bufio.NewReader(os.Stdin)
three := []byte(">THREE ")
for {
line, err := in.ReadSlice('\n')
if err != nil {
fmt.Fprintln(os.Stderr, "ReadLine err:", err)
os.Exit(2)
}
if line[0] == '>' && bytes.Equal(line[0:len(three)], three) {
break
}
}
data, err := ioutil.ReadAll(in)
if err != nil {
fmt.Fprintln(os.Stderr, "ReadAll err:", err)
os.Exit(2)
}
// delete the newlines and convert to upper case
j := 0
for i := 0; i < len(data); i++ {
if data[i] != '\n' {
data[j] = data[i] &^ ' ' // upper case
j++
}
}
str := string(data[0:j])
print(count(str, 1))
fmt.Print("\n")
print(count(str, 2))
fmt.Print("\n")
interests := []string{"GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT"}
for _, s := range interests {
fmt.Printf("%d %s\n", countOne(str, s), s)
}
}
T 31.520
A 29.600
C 19.480
G 19.400
AT 9.922
TT 9.602
TA 9.402
AA 8.402
GA 6.321
TC 6.301
TG 6.201
GT 6.041
CT 5.961
AG 5.841
CA 5.461
AC 5.441
CC 4.041
CG 4.021
GC 3.701
GG 3.341
54 GGT
24 GGTA
4 GGTATT
0 GGTATTTTAATT
0 GGTATTTTAATTTATAGT
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Shootout
http://shootout.alioth.debian.org/
contributed by Greg Buchholz
for the debian (AMD) machine...
compile flags: -O3 -ffast-math -march=athlon-xp -funroll-loops
for the gp4 (Intel) machine...
compile flags: -O3 -ffast-math -march=pentium4 -funroll-loops
*/
#include<stdio.h>
int main (int argc, char **argv)
{
int w, h, bit_num = 0;
char byte_acc = 0;
int i, iter = 50;
double x, y, limit = 2.0;
double Zr, Zi, Cr, Ci, Tr, Ti;
w = h = atoi(argv[1]);
printf("P4\n%d %d\n",w,h);
for(y=0;y<h;++y)
{
for(x=0;x<w;++x)
{
Zr = Zi = Tr = Ti = 0.0;
Cr = (2.0*x/w - 1.5); Ci=(2.0*y/h - 1.0);
for (i=0;i<iter && (Tr+Ti <= limit*limit);++i)
{
Zi = 2.0*Zr*Zi + Ci;
Zr = Tr - Ti + Cr;
Tr = Zr * Zr;
Ti = Zi * Zi;
}
byte_acc <<= 1;
if(Tr+Ti <= limit*limit) byte_acc |= 0x01;
++bit_num;
if(bit_num == 8)
{
putc(byte_acc,stdout);
byte_acc = 0;
bit_num = 0;
}
else if(x == w-1)
{
byte_acc <<= (8-w%8);
putc(byte_acc,stdout);
byte_acc = 0;
bit_num = 0;
}
}
}
}
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
* Based on mandelbrot.c contributed by Greg Buchholz
*/
package main
import (
"bufio"
"flag"
"fmt"
"os"
)
var n = flag.Int("n", 200, "size")
func main() {
flag.Parse()
out := bufio.NewWriter(os.Stdout)
defer out.Flush()
w := float64(*n)
h := float64(*n)
bit_num := 0
byte_acc := byte(0)
const Iter = 50
const Zero float64 = 0
const Limit = 2.0
fmt.Fprintf(out, "P4\n%d %d\n", *n, *n)
for y := 0.0; y < h; y++ {
for x := 0.0; x < w; x++ {
Zr, Zi, Tr, Ti := Zero, Zero, Zero, Zero
Cr := (2*x/w - 1.5)
Ci := (2*y/h - 1.0)
for i := 0; i < Iter && (Tr+Ti <= Limit*Limit); i++ {
Zi = 2*Zr*Zi + Ci
Zr = Tr - Ti + Cr
Tr = Zr * Zr
Ti = Zi * Zi
}
byte_acc <<= 1
if Tr+Ti <= Limit*Limit {
byte_acc |= 0x01
}
bit_num++
if bit_num == 8 {
out.WriteByte(byte_acc)
byte_acc = 0
bit_num = 0
} else if x == w-1 {
byte_acc <<= uint(8 - uint(*n)%8)
out.WriteByte(byte_acc)
byte_acc = 0
bit_num = 0
}
}
}
}
This diff is collapsed.
This diff is collapsed.
2098 solutions found
0 0 0 0 1
2 2 2 0 1
2 6 6 1 1
2 6 1 5 5
8 6 5 5 5
8 6 3 3 3
4 8 8 9 3
4 4 8 9 3
4 7 4 7 9
7 7 7 9 9
9 9 9 9 8
9 6 6 8 5
6 6 8 8 5
6 8 2 5 5
7 7 7 2 5
7 4 7 2 0
1 4 2 2 0
1 4 4 0 3
1 4 0 0 3
1 1 3 3 3
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*
* The Great Computer Language Shootout
* http://shootout.alioth.debian.org/
*
* contributed by Christoph Bauer
*
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define pi 3.141592653589793
#define solar_mass (4 * pi * pi)
#define days_per_year 365.24
struct planet {
double x, y, z;
double vx, vy, vz;
double mass;
};
void advance(int nbodies, struct planet * bodies, double dt)
{
int i, j;
for (i = 0; i < nbodies; i++) {
struct planet * b = &(bodies[i]);
for (j = i + 1; j < nbodies; j++) {
struct planet * b2 = &(bodies[j]);
double dx = b->x - b2->x;
double dy = b->y - b2->y;
double dz = b->z - b2->z;
double distance = sqrt(dx * dx + dy * dy + dz * dz);
double mag = dt / (distance * distance * distance);
b->vx -= dx * b2->mass * mag;
b->vy -= dy * b2->mass * mag;
b->vz -= dz * b2->mass * mag;
b2->vx += dx * b->mass * mag;
b2->vy += dy * b->mass * mag;
b2->vz += dz * b->mass * mag;
}
}
for (i = 0; i < nbodies; i++) {
struct planet * b = &(bodies[i]);
b->x += dt * b->vx;
b->y += dt * b->vy;
b->z += dt * b->vz;
}
}
double energy(int nbodies, struct planet * bodies)
{
double e;
int i, j;
e = 0.0;
for (i = 0; i < nbodies; i++) {
struct planet * b = &(bodies[i]);
e += 0.5 * b->mass * (b->vx * b->vx + b->vy * b->vy + b->vz * b->vz);
for (j = i + 1; j < nbodies; j++) {
struct planet * b2 = &(bodies[j]);
double dx = b->x - b2->x;
double dy = b->y - b2->y;
double dz = b->z - b2->z;
double distance = sqrt(dx * dx + dy * dy + dz * dz);
e -= (b->mass * b2->mass) / distance;
}
}
return e;
}
void offset_momentum(int nbodies, struct planet * bodies)
{
double px = 0.0, py = 0.0, pz = 0.0;
int i;
for (i = 0; i < nbodies; i++) {
px += bodies[i].vx * bodies[i].mass;
py += bodies[i].vy * bodies[i].mass;
pz += bodies[i].vz * bodies[i].mass;
}
bodies[0].vx = - px / solar_mass;
bodies[0].vy = - py / solar_mass;
bodies[0].vz = - pz / solar_mass;
}
#define NBODIES 5
struct planet bodies[NBODIES] = {
{ /* sun */
0, 0, 0, 0, 0, 0, solar_mass
},
{ /* jupiter */
4.84143144246472090e+00,
-1.16032004402742839e+00,
-1.03622044471123109e-01,
1.66007664274403694e-03 * days_per_year,
7.69901118419740425e-03 * days_per_year,
-6.90460016972063023e-05 * days_per_year,
9.54791938424326609e-04 * solar_mass
},
{ /* saturn */
8.34336671824457987e+00,
4.12479856412430479e+00,
-4.03523417114321381e-01,
-2.76742510726862411e-03 * days_per_year,
4.99852801234917238e-03 * days_per_year,
2.30417297573763929e-05 * days_per_year,
2.85885980666130812e-04 * solar_mass
},
{ /* uranus */
1.28943695621391310e+01,
-1.51111514016986312e+01,
-2.23307578892655734e-01,
2.96460137564761618e-03 * days_per_year,
2.37847173959480950e-03 * days_per_year,
-2.96589568540237556e-05 * days_per_year,
4.36624404335156298e-05 * solar_mass
},
{ /* neptune */
1.53796971148509165e+01,
-2.59193146099879641e+01,
1.79258772950371181e-01,
2.68067772490389322e-03 * days_per_year,
1.62824170038242295e-03 * days_per_year,
-9.51592254519715870e-05 * days_per_year,
5.15138902046611451e-05 * solar_mass
}
};
int main(int argc, char ** argv)
{
int n = atoi(argv[1]);
int i;
offset_momentum(NBODIES, bodies);
printf ("%.9f\n", energy(NBODIES, bodies));
for (i = 1; i <= n; i++)
advance(NBODIES, bodies, 0.01);
printf ("%.9f\n", energy(NBODIES, bodies));
return 0;
}
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
* based on C program by Christoph Bauer
*/
package main
import (
"flag"
"fmt"
"math"
)
var n = flag.Int("n", 1000, "number of iterations")
type Body struct {
x, y, z, vx, vy, vz, mass float64
}
const (
solarMass = 4 * math.Pi * math.Pi
daysPerYear = 365.24
)
func (b *Body) offsetMomentum(px, py, pz float64) {
b.vx = -px / solarMass
b.vy = -py / solarMass
b.vz = -pz / solarMass
}
type System []*Body
func NewSystem(body []Body) System {
n := make(System, len(body))
for i := 0; i < len(body); i++ {
n[i] = new(Body) // copy to avoid overwriting the inputs
*n[i] = body[i]
}
var px, py, pz float64
for _, body := range n {
px += body.vx * body.mass
py += body.vy * body.mass
pz += body.vz * body.mass
}
n[0].offsetMomentum(px, py, pz)
return n
}
func (sys System) energy() float64 {
var e float64
for i, body := range sys {
e += 0.5 * body.mass *
(body.vx*body.vx + body.vy*body.vy + body.vz*body.vz)
for j := i + 1; j < len(sys); j++ {
body2 := sys[j]
dx := body.x - body2.x
dy := body.y - body2.y
dz := body.z - body2.z
distance := math.Sqrt(dx*dx + dy*dy + dz*dz)
e -= (body.mass * body2.mass) / distance
}
}
return e
}
func (sys System) advance(dt float64) {
for i, body := range sys {
for j := i + 1; j < len(sys); j++ {
body2 := sys[j]
dx := body.x - body2.x
dy := body.y - body2.y
dz := body.z - body2.z
dSquared := dx*dx + dy*dy + dz*dz
distance := math.Sqrt(dSquared)
mag := dt / (dSquared * distance)
body.vx -= dx * body2.mass * mag
body.vy -= dy * body2.mass * mag
body.vz -= dz * body2.mass * mag
body2.vx += dx * body.mass * mag
body2.vy += dy * body.mass * mag
body2.vz += dz * body.mass * mag
}
}
for _, body := range sys {
body.x += dt * body.vx
body.y += dt * body.vy
body.z += dt * body.vz
}
}
var (
jupiter = Body{
x: 4.84143144246472090e+00,
y: -1.16032004402742839e+00,
z: -1.03622044471123109e-01,
vx: 1.66007664274403694e-03 * daysPerYear,
vy: 7.69901118419740425e-03 * daysPerYear,
vz: -6.90460016972063023e-05 * daysPerYear,
mass: 9.54791938424326609e-04 * solarMass,
}
saturn = Body{
x: 8.34336671824457987e+00,
y: 4.12479856412430479e+00,
z: -4.03523417114321381e-01,
vx: -2.76742510726862411e-03 * daysPerYear,
vy: 4.99852801234917238e-03 * daysPerYear,
vz: 2.30417297573763929e-05 * daysPerYear,
mass: 2.85885980666130812e-04 * solarMass,
}
uranus = Body{
x: 1.28943695621391310e+01,
y: -1.51111514016986312e+01,
z: -2.23307578892655734e-01,
vx: 2.96460137564761618e-03 * daysPerYear,
vy: 2.37847173959480950e-03 * daysPerYear,
vz: -2.96589568540237556e-05 * daysPerYear,
mass: 4.36624404335156298e-05 * solarMass,
}
neptune = Body{
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * daysPerYear,
vy: 1.62824170038242295e-03 * daysPerYear,
vz: -9.51592254519715870e-05 * daysPerYear,
mass: 5.15138902046611451e-05 * solarMass,
}
sun = Body{
mass: solarMass,
}
)
func main() {
flag.Parse()
system := NewSystem([]Body{sun, jupiter, saturn, uranus, neptune})
fmt.Printf("%.9f\n", system.energy())
for i := 0; i < *n; i++ {
system.advance(0.01)
}
fmt.Printf("%.9f\n", system.energy())
}
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
http://shootout.alioth.debian.org/
contributed by Paolo Bonzini & Sean Bartlett
modified by Michael Mellor
*/
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
static mpz_t numer, accum, denom, tmp1, tmp2;
static int extract_digit()
{
if (mpz_cmp(numer, accum) > 0)
return -1;
/* Compute (numer * 3 + accum) / denom */
mpz_mul_2exp(tmp1, numer, 1);
mpz_add(tmp1, tmp1, numer);
mpz_add(tmp1, tmp1, accum);
mpz_fdiv_qr(tmp1, tmp2, tmp1, denom);
/* Now, if (numer * 4 + accum) % denom... */
mpz_add(tmp2, tmp2, numer);
/* ... is normalized, then the two divisions have the same result. */
if (mpz_cmp(tmp2, denom) >= 0)
return -1;
return mpz_get_ui(tmp1);
}
static void next_term(unsigned int k)
{
unsigned int y2 = k*2 + 1;
mpz_mul_2exp(tmp1, numer, 1);
mpz_add(accum, accum, tmp1);
mpz_mul_ui(accum, accum, y2);
mpz_mul_ui(numer, numer, k);
mpz_mul_ui(denom, denom, y2);
}
static void eliminate_digit(unsigned int d)
{
mpz_submul_ui(accum, denom, d);
mpz_mul_ui(accum, accum, 10);
mpz_mul_ui(numer, numer, 10);
}
static void pidigits(unsigned int n)
{
int d;
unsigned int i = 0, k = 0, m;
mpz_init(tmp1);
mpz_init(tmp2);
mpz_init_set_ui(numer, 1);
mpz_init_set_ui(accum, 0);
mpz_init_set_ui(denom, 1);
for(;;)
{
do {
k++;
next_term(k);
d = extract_digit();
} while(d == -1);
putchar(d + '0');
i++;
m = i%10;
if(m == 0)
printf("\t:%d\n", i);
if(i >= n)
break;
eliminate_digit(d);
}
if(m) {
m = 10 - m;
while(m--)
putchar(' ');
printf("\t:%d\n", n);
}
}
int main(int argc, char **argv)
{
pidigits(argc > 1 ? atoi(argv[1]) : 27);
return 0;
}
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by The Go Authors.
* based on pidigits.c (by Paolo Bonzini & Sean Bartlett,
* modified by Michael Mellor)
*/
package main
import (
"flag"
"fmt"
"math/big"
)
var n = flag.Int("n", 27, "number of digits")
var silent = flag.Bool("s", false, "don't print result")
var (
tmp1 = big.NewInt(0)
tmp2 = big.NewInt(0)
tmp3 = big.NewInt(0)
y2 = big.NewInt(0)
bigk = big.NewInt(0)
numer = big.NewInt(1)
accum = big.NewInt(0)
denom = big.NewInt(1)
ten = big.NewInt(10)
)
func extract_digit() int64 {
if numer.Cmp(accum) > 0 {
return -1
}
// Compute (numer * 3 + accum) / denom
tmp1.Lsh(numer, 1)
tmp1.Add(tmp1, numer)
tmp1.Add(tmp1, accum)
tmp1.DivMod(tmp1, denom, tmp2)
// Now, if (numer * 4 + accum) % denom...
tmp2.Add(tmp2, numer)
// ... is normalized, then the two divisions have the same result.
if tmp2.Cmp(denom) >= 0 {
return -1
}
return tmp1.Int64()
}
func next_term(k int64) {
y2.SetInt64(k*2 + 1)
bigk.SetInt64(k)
tmp1.Lsh(numer, 1)
accum.Add(accum, tmp1)
accum.Mul(accum, y2)
numer.Mul(numer, bigk)
denom.Mul(denom, y2)
}
func eliminate_digit(d int64) {
tmp3.SetInt64(d)
accum.Sub(accum, tmp3.Mul(denom, tmp3))
accum.Mul(accum, ten)
numer.Mul(numer, ten)
}
func printf(s string, arg ...interface{}) {
if !*silent {
fmt.Printf(s, arg...)
}
}
func main() {
flag.Parse()
var m int // 0 <= m < 10
for i, k := 0, int64(0); ; {
d := int64(-1)
for d < 0 {
k++
next_term(k)
d = extract_digit()
}
printf("%c", d+'0')
i++
m = i % 10
if m == 0 {
printf("\t:%d\n", i)
}
if i >= *n {
break
}
eliminate_digit(d)
}
if m > 0 {
printf("%s\t:%d\n", " "[m:10], *n)
}
}
3141592653 :10
5897932384 :20
6264338 :27
This diff is collapsed.
agggtaaa|tttaccct 1
[cgt]gggtaaa|tttaccc[acg] 0
a[act]ggtaaa|tttacc[agt]t 0
ag[act]gtaaa|tttac[agt]ct 0
agg[act]taaa|ttta[agt]cct 1
aggg[acg]aaa|ttt[cgt]ccct 0
agggt[cgt]aa|tt[acg]accct 0
agggta[cgt]a|t[acg]taccct 0
agggtaa[cgt]|[acg]ttaccct 2
10245
10000
13348
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment