Commit 6606795d by songxinkai

init

parents
cc_library(
name="cls0",
srcs=["cls0.cpp"],
hdrs=["cls0.hpp"],
visibility=["//visibility:public"],
)
#include "cls0.hpp"
cls0::cls0(){
m_count = 0;
}
cls0::~cls0(){
}
int cls0::get_count(){
return m_count;
}
void cls0::add_data(float dat){
m_data.push_back(dat);
m_count ++;
}
#ifndef CLS0_HPP
#define CLS0_HPP
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
class cls0 {
public:
cls0();
~cls0();
int get_count();
void add_data(float );
private:
int m_count;
vector<float> m_data;
};
#endif
local_repository(
# the name will be used in BUILD file of this repository(deps = ["@example0//some_module:some_lib_name"]);
name="repo0",
# absolute path of the directory containing the target repository's WORKSPACE file
#path="/root/mytests/bazel/repo0"
# relative path to the main repository's WORKSPACE file(this file)
path="../repo0"
)
/root/.cache/bazel/_bazel_root/3ca51cb9a7e10b81b1009271d77d0cd3/execroot/__main__/bazel-out/k8-fastbuild/bin
\ No newline at end of file
/root/.cache/bazel/_bazel_root/3ca51cb9a7e10b81b1009271d77d0cd3/execroot/__main__/bazel-out/k8-fastbuild/genfiles
\ No newline at end of file
/root/.cache/bazel/_bazel_root/3ca51cb9a7e10b81b1009271d77d0cd3/execroot/__main__/bazel-out
\ No newline at end of file
/root/.cache/bazel/_bazel_root/3ca51cb9a7e10b81b1009271d77d0cd3/execroot/__main__
\ No newline at end of file
/root/.cache/bazel/_bazel_root/3ca51cb9a7e10b81b1009271d77d0cd3/execroot/__main__/bazel-out/k8-fastbuild/testlogs
\ No newline at end of file
cc_binary(
name = "main",
# @ mark in deps means it comes from WORKSPACE
deps = ["@repo0//module0:cls0"],
srcs = ["main.cpp",],
)
cc_binary(
name = "main1",
deps = ["@repo0//module0:cls0"],
srcs = ["main1.cpp",],
)
// head file here is the relative path to the root directory of external repository
#include "module0/cls0.hpp"
int main(){
cls0 c0;
c0.add_data(0.1);
cout << c0.get_count() << endl;
return 0;
}
#include "module0/cls0.hpp"
int main (){
cout << "this is repo1/module1/main1" << endl;
return 0;
}
//the following are UBUNTU/LINUX ONLY terminal color codes.
//#define RESET "\033[0m"
//#define BLACK "\033[30m" /* Black */
//#define RED "\033[31m" /* Red */
//#define GREEN "\033[32m" /* Green */
//#define YELLOW "\033[33m" /* Yellow */
//#define BLUE "\033[34m" /* Blue */
//#define MAGENTA "\033[35m" /* Magenta */
//#define CYAN "\033[36m" /* Cyan */
//#define WHITE "\033[37m" /* White */
//#define BOLDBLACK "\033[1m\033[30m" /* Bold Black */
//#define BOLDRED "\033[1m\033[31m" /* Bold Red */
//#define BOLDGREEN "\033[1m\033[32m" /* Bold Green */
//#define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */
//#define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */
//#define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */
//#define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */
//#define BOLDWHITE "\033[1m\033[37m" /* Bold White */
cout << "\033[32m" << " new win";
#include <iostream>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
using namespace std;
int main(){
//cout << fs::exist("a") << endl;
//cout << fs::exist("b") << endl;
cout << fs::is_directory("b") << endl;
return 0;
}
#include <unistd.h>
#include <iostream>
using namespace std;
int main (){
char file_name[] = "b";
if ( 0 == access(file_name, 0) ) cout<<"access(): path exist."<<endl;
return 0;
}
#include <unistd.h>
#include <sys/syscall.h>
#include <iostream>
#include <string>
using namespace std;
void print_pid(char* s, int& a){
cout << s << ", pid: " << syscall(__NR_getpid) << ", tid: " << syscall(__NR_gettid) << endl;
s = "2";
a ++;
}
int main(){
int a = 0;
print_pid("1", a);
char* s = "sxk ";
pid_t child_pid;
child_pid = fork();
print_pid(s, a);
cout << a << ", " << &a << endl;
child_pid = fork();
print_pid(s, a);
cout << a << ", " << &a << endl;
child_pid = fork();
print_pid(s, a);
cout << a << ", " << &a << endl;
return 0;
}
File added
/usr/lib/python2.7/config-x86_64-linux-gnu/libpython2.7.so
\ No newline at end of file
import numpy as np
def save_np(input_data, fn):
a = np.array(input_data)
a.tofile(fn)
def load_np(fn):
b = np.fromfile(fn, dtype=np.float)
print b.shape
#s = ''
#for i in b:
# s += "%1.1f "%i
#print s
/**g++ -o callpy callpy.cpp -I/usr/include/python2.7 -L/usr/lib64/python2.7/config -lpython2.7**/
#include <Python.h>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <iostream>
#include <sstream>
using namespace std;
mutex mtx;
void py_save_load(int thread_id){
mtx.lock();
Py_Initialize() ;
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
mtx.unlock();
mtx.lock();
PyObject *pName,*pModule,*pDict,*pFunc,*pArgs;
pName = PyString_FromString("np_file");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "save_np");
pArgs = PyTuple_New(2);
int len = 10000;
PyObject* tuple_0 = PyTuple_New(len);
for (int i = 0; i < len; ++i){
PyTuple_SetItem(tuple_0, i, Py_BuildValue("f",0.1*i));
}
stringstream ss;
ss << "out" << thread_id << ".bin";
string s = ss.str();
PyTuple_SetItem(pArgs, 0, Py_BuildValue("O", tuple_0));
PyTuple_SetItem(pArgs, 1, Py_BuildValue("s",s.c_str()));
PyObject_CallObject(pFunc, pArgs);
pFunc = PyDict_GetItemString(pDict, "load_np");
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs, 0, Py_BuildValue("s",s.c_str()));
PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pName);
Py_DECREF(pArgs);
Py_DECREF(pModule);
mtx.unlock();
}
int main(int argc, char** argv){
cout << std::dec << 15 << endl;
vector<thread> ths;
for (int i = 0; i < 8; ++i){
ths.emplace_back(py_save_load, i);
}
for (auto& th: ths){
th.join();
}
cout << "=============" << endl;
return 0;
}
File added
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i,j;
srand((int)time(0));
for(i=0; i<10; i++)
{
j=1+(int)(10.0 * rand()/(RAND_MAX+1.0));
printf("%d ",j);
}
printf("\n");
}
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i,j;
for(i=0; i<10; i++)
{
printf("%d ",rand());
}
}
#include <random>
#include <iostream>
using namespace std;
static thread_local std::random_device g_random_device;
static thread_local std::minstd_rand g_random_engine(g_random_device());
int N = 100;
int main(){
int min = 999999999;
int max = -1;
for (int i = 0; i < N; ++i){
int a = g_random_engine();
cout << int(g_random_engine() % 10) << ", ";
}
cout << endl;
return 0;
}
File added
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
using namespace std;
int main(){
for (int i = 0; i < 10; ++i){
sleep(2);
cout << "1" << endl;
usleep(2000000);
cout << "2" << endl;
}
return 0;
}
File added
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
void i2s(int i, string& s){
stringstream ss;
ss << i;
ss >> s;
}
void s2i(string s, int& i){
stringstream ss(s);
ss >> i;
}
vector<string> string_split(const string &s, const string &seperator){
vector<string> result;
typedef string::size_type string_size;
string_size i = 0;
while(i != s.size()){
int flag = 0;
while(i != s.size() && flag == 0){
flag = 1;
for(string_size x = 0; x < seperator.size(); ++x)
if(s[i] == seperator[x]){
++i;
flag = 0;
break;
}
}
flag = 0;
string_size j = i;
while(j != s.size() && flag == 0){
for(string_size x = 0; x < seperator.size(); ++x)
if(s[j] == seperator[x]){
flag = 1;
break;
}
if(flag == 0)
++j;
}
if(i != j){
result.push_back(s.substr(i, j-i));
i = j;
}
}
return result;
}
int main(){
int i1 = 199, i21, i22;
string s1, s2="288_377", s3 = "finish";
i2s(i1, s1);
vector<string> vec_s = string_split(s2, "_");
s2i(vec_s[0], i21);
s2i(vec_s[1], i22);
cout << ("finish" == s3) << ", " << ("288" == s3) << endl;
cout << i1 << ", " << s1 << endl;
cout << s2 << ", " << i21 << " _ " << i22 << endl;
return 0;
}
#include <string>
#include <iostream>
using namespace std;
int main(){
string a("aaaaassfaaaaa ff ");
string b("ccc");
string c("ff");
cout << string::npos << endl;
cout << a.find(b) << endl;
cout << a.find(c) << endl;
cout << a.find("f") << endl;
return 0;
}
File added
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
stringstream ss;
string s = "c.";
system("nvidia-smi");
system(("touch " + s + "out").c_str());
ss << "mv " << "c.out " << "b.out";
system(ss.str().c_str());
return 0;
}
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An Example of a custom Estimator for the Iris dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import tensorflow as tf
import numpy as np
import my_iris_data as iris_data
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', default=100, type=int, help='batch size')
parser.add_argument('--train_steps', default=1000, type=int,
help='number of training steps')
def my_model(features, labels, mode, params):
"""DNN with three hidden layers, and dropout of 0.1 probability."""
# Create three fully connected layers each layer having a dropout
# probability of 0.1.
for units in params['hidden_units']:
net = tf.layers.dense(features, units=units, activation=tf.nn.relu)
# Compute logits (1 per class).
logits = tf.layers.dense(net, params['n_classes'], activation=None)
# Compute predictions.
predicted_classes = tf.argmax(logits, 1)
if mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
'class_ids': predicted_classes[:, tf.newaxis],
'probabilities': tf.nn.softmax(logits),
'logits': logits,
}
return tf.estimator.EstimatorSpec(mode, predictions=predictions)
# Compute loss.
loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
# Compute evaluation metrics.
accuracy = tf.metrics.accuracy(labels=labels,
predictions=predicted_classes,
name='acc_op')
metrics = {'accuracy': accuracy}
tf.summary.scalar('accuracy', accuracy[1])
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(
mode, loss=loss, eval_metric_ops=metrics)
# Create training op.
assert mode == tf.estimator.ModeKeys.TRAIN
optimizer = tf.train.AdagradOptimizer(learning_rate=0.1)
train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)
# Define data loaders #####################################
class IteratorInitializerHook(tf.train.SessionRunHook):
"""Hook to initialise data iterator after Session is created."""
def __init__(self):
super(IteratorInitializerHook, self).__init__()
self.iterator_initializer_func = None
def after_create_session(self, session, coord):
"""Initialise the iterator after the session has been created."""
self.iterator_initializer_func(session)
def main(argv):
args = parser.parse_args(argv[1:])
# Fetch the data
(train_x_1, train_y_1), (test_x, test_y) = iris_data.load_data()
train_x_1 = np.array(train_x_1)
train_y_1 = np.array(train_y_1)
test_x = np.array(test_x)
test_y = np.array(test_y)
train_x = train_x_1.copy()
train_y = train_y_1.copy()
for i in range(100):
train_x = np.append(train_x, train_x_1, 0)
train_y = np.append(train_y, train_y_1)
print (train_x.shape, train_y.shape)
# Build 2 hidden layer DNN with 10, 10 units respectively.
classifier = tf.estimator.Estimator(
model_fn=my_model,
params={
'hidden_units': [10, 10],
'n_classes': 3,
})
iterator_initializer_hook = IteratorInitializerHook()
# Train the Model.
classifier.train(
input_fn=lambda:iris_data.train_input_fn(train_x, train_y, args.batch_size, iterator_initializer_hook),
hooks=[iterator_initializer_hook],
steps=args.train_steps)
# Evaluate the model.
eval_result = classifier.evaluate(
input_fn=lambda:iris_data.eval_input_fn(test_x, test_y, args.batch_size))
print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result))
# Generate predictions from the model
expected = ['Setosa', 'Versicolor', 'Virginica']
predict_x = [[5.1, 5.9, 6.9],
[3.3, 3.0, 3.1],
[1.7, 4.2, 5.4],
[0.5, 1.5, 2.1]]
predict_x = np.transpose(np.array(predict_x))
predictions = classifier.predict(
input_fn=lambda:iris_data.eval_input_fn(predict_x,
labels=None,
batch_size=args.batch_size))
for pred_dict, expec in zip(predictions, expected):
template = ('\nPrediction is "{}" ({:.1f}%), expected "{}"')
class_id = pred_dict['class_ids'][0]
probability = pred_dict['probabilities'][class_id]
print(template.format(iris_data.SPECIES[class_id],
100 * probability, expec))
if __name__ == '__main__':
tf.logging.set_verbosity(tf.logging.INFO)
tf.app.run(main)
import pandas as pd
import tensorflow as tf
TRAIN_URL = "http://download.tensorflow.org/data/iris_training.csv"
TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"
CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth',
'PetalLength', 'PetalWidth', 'Species']
SPECIES = ['Setosa', 'Versicolor', 'Virginica']
def maybe_download():
train_path = tf.keras.utils.get_file(TRAIN_URL.split('/')[-1], TRAIN_URL)
test_path = tf.keras.utils.get_file(TEST_URL.split('/')[-1], TEST_URL)
return train_path, test_path
def load_data(y_name='Species'):
"""Returns the iris dataset as (train_x, train_y), (test_x, test_y)."""
train_path, test_path = maybe_download()
train = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)
train_x, train_y = train, train.pop(y_name)
test = pd.read_csv(test_path, names=CSV_COLUMN_NAMES, header=0)
test_x, test_y = test, test.pop(y_name)
return (train_x, train_y), (test_x, test_y)
def train_input_fn(features, labels, batch_size, hook):
#dataset = tf.data.Dataset.from_tensor_slices((features, labels))
#dataset = dataset.shuffle(1000).repeat().batch(batch_size)
#return dataset
assert features.shape[0] == labels.shape[0]
features_placeholder = tf.placeholder(features.dtype, features.shape)
labels_placeholder = tf.placeholder(labels.dtype, labels.shape)
dataset = tf.data.Dataset.from_tensor_slices((features_placeholder, labels_placeholder))
dataset = dataset.shuffle(features.shape[0]).repeat().batch(batch_size)
iterator = dataset.make_initializable_iterator()
next_element = iterator.get_next()
hook.iterator_initializer_func = \
lambda sess: sess.run(
iterator.initializer,
feed_dict={features_placeholder: features, labels_placeholder: labels})
#sess = tf.Session()
#sess.run(iterator.initializer, feed_dict={features_placeholder: features, labels_placeholder: labels})
return next_element
def eval_input_fn(features, labels, batch_size):
"""An input function for evaluation or prediction"""
if labels is None:
# No labels, use only features.
inputs = features
else:
inputs = (features, labels)
# Convert the inputs to a Dataset.
dataset = tf.data.Dataset.from_tensor_slices(inputs)
# Batch the examples
assert batch_size is not None, "batch_size must not be None"
dataset = dataset.batch(batch_size)
# Return the dataset.
return dataset
# The remainder of this file contains a simple example of a csv parser,
# implemented using the `Dataset` class.
# `tf.parse_csv` sets the types of the outputs to match the examples given in
# the `record_defaults` argument.
CSV_TYPES = [[0.0], [0.0], [0.0], [0.0], [0]]
def _parse_line(line):
# Decode the line into its fields
fields = tf.decode_csv(line, record_defaults=CSV_TYPES)
# Pack the result into a dictionary
features = dict(zip(CSV_COLUMN_NAMES, fields))
# Separate the label from the features
label = features.pop('Species')
return features, label
def csv_input_fn(csv_path, batch_size):
# Create a dataset containing the text lines.
dataset = tf.data.TextLineDataset(csv_path).skip(1)
# Parse each line.
dataset = dataset.map(_parse_line)
# Shuffle, repeat, and batch the examples.
dataset = dataset.shuffle(1000).repeat().batch(batch_size)
# Return the dataset.
return dataset
#include <string>
#include <memory>
#include <boost/filesystem.hpp>
#include <glog/logging.h>
#include <gflags/gflags.h>
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
namespace fs = boost::filesystem;
namespace tf = tensorflow;
DEFINE_string(meta_graph_def, "meta_graph", "Path to meta_graph.");
DEFINE_string(checkpoint_path, "checkpoint", "Path to checkpoint.");
FLAGS_log_dir = "logs/";
int main(int argc, char* argv[]){
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
std::unique_ptr<tensorflow::Session> sess;
tf::MetaGraphDef meta_graph_def;
tf::Status status = ReadBinaryProto(tf::Env::Default(), FLAGS_meta_graph_path, &meta_graph_def);
LOG(INFO) << ;
status = sess->Create(meta_graph_def);
tf::Tensor checkpoint_path_tensor(tf::DT_STRING, tf::TensorShape());
checkpoint_path_tensor.scalar<std::string>()() = FLAGS_checkpoint_path;
status = sess->Run({},
{}, /* fetches_outputs is empty */
{},
nullptr
);
return 0;
}
File added
File added
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
void f1(int n)
{
for (int i = 0; i < n; ++i) {
std::cout << "Thread 1: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int n)
{
for (int i = 0; i < n; ++i) {
std::cout << "Thread 2: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main()
{
int n = 100;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n); // pass by value
std::thread t3(f2, n); // pass by reference
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
std::thread t5(f2, n); // pass by reference
t2.join();
t4.join();
t5.join();
std::cout << "Finish!" << std::endl;
}
File added
#include <iostream>
int main()
{
int n = 0;
int a = 1;
std::cout << "Final value of n is " << n << '\n';
}
#include <iostream>
#include <functional>
#include <thread>
#include <atomic>
using namespace std;
void fn1 (int& a, int N){
for (int i = 0; i < N; ++i){
a ++;
}
}
void fn2 (int& a, int N){
for (int i = 0; i < N; ++i){
a ++;
}
}
void at_fn1 (atomic<int>* a, int N){
for (int i = 0; i < N; ++i){
(*a) ++;
}
}
void at_fn2 (atomic<int>* a, int N){
for (int i = 0; i < N; ++i){
(*a) ++;
}
}
int main(){
int N = 100;
int a = 0;
int error_count = 0;
for (int i = 0; i < N; ++i){
a = 0;
thread t1(fn1, ref(a), 10000);
thread t2(fn2, ref(a), 10000);
t1.join();
t2.join();
if (a != 20000) error_count ++;
}
cout << float(error_count) / N << endl;
atomic<int> at_a(0);
error_count = 0;
for (int i = 0; i < N; ++i){
at_a = 0;
thread t1(at_fn1, &at_a, 10000);
thread t2(at_fn2, &at_a, 10000);
t1.join();
t2.join();
if (at_a.load() != 20000) error_count ++;
}
cout << float(error_count) / N << endl;
return 0;
}
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
using namespace std;
void at_fn1 (atomic<int>* a, int N){
for (int i = 0; i < N; ++i){
(*a) ++;
}
}
int main(){
int N = 10, M = 100;
vector<thread> my_ths;
atomic<int> at_a(1);
for (int i = 0; i < N; ++i){
my_ths.emplace_back(at_fn1, &at_a, 10000);
}
for (auto &th: my_ths){
th.join();
}
cout << at_a.load() << endl;
return 0;
}
#!/bin/bash
g++ -g -pthread -fpic -std=c++11 -o main main.cpp
File added
#include <unistd.h>
#include <iostream>
#include <time.h>
using namespace std;
int main(){
time_t a = 0, b;
if (a == 0){
cout << "xx" << endl;
}
time(&a);
sleep(4);
time(&b);
cout << a << ", " << b << endl;
cout << b -a << endl;
return 0;
}
#include <iostream>
#include <memory>
using namespace std;
class A{
public:
A(){ num = 0; }
int get_num(){ return num; }
protected:
int num;
};
int main(){
auto a = unique_ptr<A>(new A);
cout << a->get_num() << endl;
return 0;
}
File added
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
#define N 4 //BORDER_SIZE
#define WHITE -1
#define EMPTY 0
#define BLACK 1
#define FILL 2
#define KO 3
#define UNKNOWN 4
int find_one_empty(vector<int>& board);
int count_black_win_num(vector<int>& board, int& b_num, int& w_num);
bool color_in_territory(vector<int>& board, vector<int>& set, int color);
int find_reached(vector<int>& board, int idx, vector<int>& territory, vector<int>& borders);
int score(vector<int>& board, int komi, int& b_num, int& w_num);
void get_neighbor(int idx, vector<int>& neighbors);
bool inside_board(int x, int y);
bool in_territory(vector<int>& territory, int idx);
void place_stones(vector<int>& working_board, int territory_color, vector<int> territory);
void make_board(vector<int>& board, int border_size, bool display);
int main(){
vector<int> board;
int b, w;
make_board(board, N, true);
score(board, 0, b, w);
cout << " (B: " << b << ", W: " << w << ")" << endl;
return 0;
}
void make_board(vector<int>& board, int border_size, bool display){
srand((unsigned)time(NULL));
board.clear();
for (int i = 0; i < border_size*border_size; ++i){
int r = rand();
char color_c;
int color;
if (r < RAND_MAX / 5 * 2){
color_c = 'B';
color = -1;
} else if (r > RAND_MAX / 5 * 3){
color_c = 'W';
color = 1;
} else {
color_c = '0';
color = 0;
}
board.push_back(color);
if (i % N == 0) cout << endl << color_c;
else cout << ", " << color_c;
}
}
int score(vector<int>& board, int komi, int& b_num, int& w_num){
vector<int> working_board(N*N, 0);
for (int i = 0; i < N*N; ++i){
if (board[i] == -1 || board[i] == 0 || board[i] == 1){
working_board[i] = board[i];
}else{
cout << "Wrong stone in input board: " << board[i] << endl;
return -9998;
}
}
vector<int> territory;
vector<int> borders;
while (find_one_empty(working_board) != -1){
int em_id = find_one_empty(working_board);
find_reached(working_board, em_id, territory, borders);
if (color_in_territory(working_board, borders, EMPTY)){
cout << "Wrong EMPTY in borders." << endl;
return -9999;
}
bool black_in_border = color_in_territory(working_board, borders, BLACK);
bool white_in_border = color_in_territory(working_board, borders, WHITE);
int territory_color;
if (black_in_border && !white_in_border){
territory_color = BLACK;
} else if (!black_in_border && white_in_border){
territory_color = WHITE;
} else {
territory_color = UNKNOWN;
}
place_stones(working_board, territory_color, territory);
}
return count_black_win_num(working_board, b_num, w_num) - komi;
}
void place_stones(vector<int>& working_board, int territory_color, vector<int> territory){
for (int i = 0; i < territory.size(); ++i){
working_board[territory[i]] = territory_color;
}
}
int find_reached(vector<int>& board, int idx, vector<int>& territory, vector<int>& borders){
int color = board[idx];
territory.clear();
borders.clear();
vector<int> frontier(1, idx);
vector<int> neighbors;
while (!frontier.empty()){
int current = frontier.back();
frontier.pop_back();
territory.push_back(current);
get_neighbor(current, neighbors);
for (int i = 0; i < neighbors.size(); ++i){
int nei_idx = neighbors[i];
if (board[nei_idx] == color && !in_territory(territory, nei_idx)){
frontier.push_back(nei_idx);
}else if (board[nei_idx] != color){
borders.push_back(nei_idx);
}
}
}
return territory.size();
}
bool in_territory(vector<int>& territory, int idx){
for (int i = 0; i < territory.size(); ++i){
if (territory[i] == idx){
return true;
}
}
return false;
}
void get_neighbor(int idx, vector<int>& neighbors){
neighbors.clear();
int y = idx / N;
int x = idx % N;
if (inside_board(x-1,y)){neighbors.push_back(idx-1);}
if (inside_board(x+1,y)){neighbors.push_back(idx+1);}
if (inside_board(x,y-1)){neighbors.push_back(idx-N);}
if (inside_board(x,y+1)){neighbors.push_back(idx+N);}
}
bool inside_board(int x, int y){
if (x >= 0 && x < N && y >= 0 && y < N){
return true;
}
return false;
}
bool color_in_territory(vector<int>& board, vector<int>& set, int color){
for (int i = 0; i < set.size(); ++i){
if (board[set[i]] == color){
return true;
}
}
return false;
}
int count_black_win_num(vector<int>& board, int& b_num, int& w_num){
int black = 0;
int white = 0;
for (int i = 0; i < N*N; ++i){
if (board[i] == BLACK){
black ++;
} else if (board[i] == WHITE){
white ++;
}
}
b_num = black;
w_num = white;
return black - white;
}
int find_one_empty(vector<int>& board){
for (int i = 0; i < N*N; ++i){
if (board[i] == EMPTY){
return i;
}
}
return -1;
}
import numpy as np
# UNKNOWN: dame or seki
WHITE, EMPTY, BLACK, FILL, KO, UNKNOWN = range(-1, 5)
N = 4
ALL_COORDS = [(i, j) for i in range(N) for j in range(N)]
def _check_bounds(c):
return 0 <= c[0] < N and 0 <= c[1] < N
NEIGHBORS = {(x, y): list(filter(_check_bounds, [
(x+1, y), (x-1, y), (x, y+1), (x, y-1)])) for x, y in ALL_COORDS}
def find_reached(board, c):
color = board[c]
chain = set([c])
reached = set()
frontier = [c]
while frontier:
current = frontier.pop()
chain.add(current)
for n in NEIGHBORS[current]:
if board[n] == color and not n in chain:
frontier.append(n)
elif board[n] != color:
reached.add(n)
return chain, reached
def place_stones(board, color, stones):
for s in stones:
board[s] = color
# board: NxN numpy array(dtype=np.int8), 0 empty, 1 black, -1 white.
# komi: int,
def score(board, komi):
working_board = np.copy(board)
while EMPTY in working_board:
unassigned_spaces = np.where(working_board == EMPTY)
# c is the first empty stone in board, is a tuple
c = (unassigned_spaces[0][0], unassigned_spaces[1][0])
territory, borders = find_reached(working_board, c)
border_colors = set(working_board[b] for b in borders)
X_border = BLACK in border_colors
O_border = WHITE in border_colors
if X_border and not O_border:
territory_color = BLACK
elif O_border and not X_border:
territory_color = WHITE
else:
territory_color = UNKNOWN # dame, or seki
place_stones(working_board, territory_color, territory)
#return np.count_nonzero(working_board == BLACK) - np.count_nonzero(working_board == WHITE) - komi
return np.count_nonzero(working_board == BLACK), np.count_nonzero(working_board == WHITE)
def produce_board():
board = (np.random.random([N,N]) * 2 - 1).round().astype(np.int8)
#board = np.zeros([N,N], dtype=np.int8)
return board
if __name__ == "__main__":
times = 10
for i in range(times):
board = produce_board()
print board, score(board, 0)
print ""
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
#define N 4 //BORDER_SIZE
#define WHITE -1
#define EMPTY 0
#define BLACK 1
#define FILL 2
#define KO 3
#define UNKNOWN 4
int find_one_empty(vector<int>& board);
int count_black_win_num(vector<int>& board, int& b_num, int& w_num);
bool color_in_territory(vector<int>& board, vector<int>& set, int color);
int find_reached(vector<int>& board, int idx, vector<int>& territory, vector<int>& borders);
int score(vector<int>& board, int komi, int& b_num, int& w_num);
void get_neighbor(int idx, vector<int>& neighbors);
bool inside_board(int x, int y);
bool in_territory(vector<int>& territory, int idx);
void place_stones(vector<int>& working_board, int territory_color, vector<int> territory);
void make_board(vector<int>& board, int border_size, bool display);
int main(){
vector<int> board;
int b, w;
make_board(board, N, true);
score(board, 0, b, w);
cout << " (B: " << b << ", W: " << w << ")" << endl;
return 0;
}
void make_board(vector<int>& board, int border_size, bool display){
srand((unsigned)time(NULL));
board.clear();
for (int i = 0; i < border_size*border_size; ++i){
int r = rand();
char color_c;
int color;
if (r < RAND_MAX / 5 * 2){
color_c = 'B';
color = -1;
} else if (r > RAND_MAX / 5 * 3){
color_c = 'W';
color = 1;
} else {
color_c = '0';
color = 0;
}
board.push_back(color);
if (i % N == 0) cout << endl << color_c;
else cout << ", " << color_c;
}
}
int score(vector<int>& board, int komi, int& b_num, int& w_num){
vector<int> working_board(N*N, 0);
for (int i = 0; i < N*N; ++i){
if (board[i] == -1 || board[i] == 0 || board[i] == 1){
working_board[i] = board[i];
}else{
cout << "Wrong stone in input board: " << board[i] << endl;
return -9998;
}
}
vector<int> territory;
vector<int> borders;
while (find_one_empty(working_board) != -1){
int em_id = find_one_empty(working_board);
find_reached(working_board, em_id, territory, borders);
if (color_in_territory(working_board, borders, EMPTY)){
cout << "Wrong EMPTY in borders." << endl;
return -9999;
}
bool black_in_border = color_in_territory(working_board, borders, BLACK);
bool white_in_border = color_in_territory(working_board, borders, WHITE);
int territory_color;
if (black_in_border && !white_in_border){
territory_color = BLACK;
} else if (!black_in_border && white_in_border){
territory_color = WHITE;
} else {
territory_color = UNKNOWN;
}
place_stones(working_board, territory_color, territory);
}
return count_black_win_num(working_board, b_num, w_num) - komi;
}
void place_stones(vector<int>& working_board, int territory_color, vector<int> territory){
for (int i = 0; i < territory.size(); ++i){
working_board[territory[i]] = territory_color;
}
}
int find_reached(vector<int>& board, int idx, vector<int>& territory, vector<int>& borders){
int color = board[idx];
territory.clear();
borders.clear();
vector<int> frontier(1, idx);
vector<int> neighbors;
while (!frontier.empty()){
int current = frontier.back();
frontier.pop_back();
territory.push_back(current);
get_neighbor(current, neighbors);
for (int i = 0; i < neighbors.size(); ++i){
int nei_idx = neighbors[i];
if (board[nei_idx] == color && !in_territory(territory, nei_idx)){
frontier.push_back(nei_idx);
}else if (board[nei_idx] != color){
borders.push_back(nei_idx);
}
}
}
return territory.size();
}
bool in_territory(vector<int>& territory, int idx){
for (int i = 0; i < territory.size(); ++i){
if (territory[i] == idx){
return true;
}
}
return false;
}
void get_neighbor(int idx, vector<int>& neighbors){
neighbors.clear();
int y = idx / N;
int x = idx % N;
if (inside_board(x-1,y)){neighbors.push_back(idx-1);}
if (inside_board(x+1,y)){neighbors.push_back(idx+1);}
if (inside_board(x,y-1)){neighbors.push_back(idx-N);}
if (inside_board(x,y+1)){neighbors.push_back(idx+N);}
}
bool inside_board(int x, int y){
if (x >= 0 && x < N && y >= 0 && y < N){
return true;
}
return false;
}
bool color_in_territory(vector<int>& board, vector<int>& set, int color){
for (int i = 0; i < set.size(); ++i){
if (board[set[i]] == color){
return true;
}
}
return false;
}
int count_black_win_num(vector<int>& board, int& b_num, int& w_num){
int black = 0;
int white = 0;
for (int i = 0; i < N*N; ++i){
if (board[i] == BLACK){
black ++;
} else if (board[i] == WHITE){
white ++;
}
}
b_num = black;
w_num = white;
return black - white;
}
int find_one_empty(vector<int>& board){
for (int i = 0; i < N*N; ++i){
if (board[i] == EMPTY){
return i;
}
}
return -1;
}
def add1(a):
with a.get_lock():
a.value += 1
import func
import time
import ctypes
from multiprocessing import Process, current_process, Lock, Semaphore, Value, Array
from multiprocessing import sharedctypes
def func0(lock, a):
lock.acquire()
print a.value
func.add1(a)
#a.value += 1
time.sleep(1)
proc = current_process()
print proc.name, proc.pid
lock.release()
lock0 = Lock()
lock = Semaphore(2) # Semaphore(1) == Lock()
v = Value('f', 0.0)
a = Array('i', range(10))
sv = sharedctypes.Value('f', 0.0)
sa = sharedctypes.Array('i', range(10))
sub_proc0 = Process(target=func0, args=(lock, sa))
sub_proc1 = Process(target=func0, args=(lock, sa))
sub_proc2 = Process(target=func0, args=(lock, sa))
sub_proc0.start()
sub_proc1.start()
sub_proc2.start()
sub_proc0.join()
sub_proc1.join()
sub_proc2.join()
func0(lock, sa)
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