CMD常用命令17常用软件注册为Widows服务

1、Apache注册为Widows服务

httpd -k install

2、MySQL注册为Widows服务

mysqld --install MySQL --defaults-file="D:\MySQL\MySQL Server 5.1\my.ini"

3、PostgreSQL注册为Widows服务

pg_ctl.exe register -N "postgresql-8.4" -D "D:/PostgreSQL/8.4/data" -w

4、SVN注册为Widows服务

sc create svnserve binPath= "\"D:\Subversion\bin\svnserve.exe\" --service -r \"D:\Subversion\repository\"" displayname= "Subversion Service" depend= Tcpip start= auto 
sc start svnserve 
sc stop svnserve 
sc delete svnserve

5、redis注册为Widows服务

#loglevel 分为debug, notice, warning三级
redis-server.exe --service-install D:\Database\Redis2.8\db\redis.windows.conf --loglevel notice
redis-server --service-start
redis-server --service-stop
redis-server --service-uninstall

6、mongodb注册为Widows服务

mongod --dbpath=D:\Database\MongoDB3\db --logpath=D:\Database\MongoDB3\log\mongo.log --port 27027 --noauth --install -serviceName MongoDB01 --serviceDisplayName MongoDB01 
net start MongoDB01

MongoDB副本集(Java)

还是蛮简单的,驱动把任务全部做掉了

package com.djhu.mongodb.test;

import java.util.Arrays;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class ReplTest
{
	private static void testInsert() 
	{
		MongoClient mongoClient = new MongoClient(Arrays.asList(
				   new ServerAddress("172.16.172.4", 27017),
				   new ServerAddress("172.16.172.4", 27018),
				   new ServerAddress("172.16.172.4", 27019)));

		MongoDatabase db = mongoClient.getDatabase("test");
		MongoCollection collection = db.getCollection("person");
		
		Document doc = new Document();
		doc.put("name", "tuzi");
		doc.put("age", 27);
		doc.put("sex", "Female");
		collection.insertOne(doc);
	}

	public static void main(String[] args)
	{
		testInsert();
	}
}

如果遇到下面的错误,是因为用了localhost作为replSet的地址,重新config一下就好了

Caused by: java.net.ConnectException: Connection refused: connect
	at java.net.PlainSocketImpl.socketConnect(Native Method)
	at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
	at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
	at java.net.Socket.connect(Socket.java:519)
	at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
	at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
	... 3 more
Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches PrimaryServerSelector. Client view of cluster state is {type=REPLICA_SET, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=localhost:27018, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=localhost:27019, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=localhost:27020, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
	at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:370)
	at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)
	at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
	at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
	at com.mongodb.binding.ClusterBinding.getWriteConnectionSource(ClusterBinding.java:68)
	at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:175)
	at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:141)
	at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:72)
	at com.mongodb.Mongo.execute(Mongo.java:747)
	at com.mongodb.Mongo$2.execute(Mongo.java:730)
	at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:482)
	at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:277)
	at com.djhu.mongodb.test.ReplTest.testInsert(ReplTest.java:28)
	at com.djhu.mongodb.test.ReplTest.main(ReplTest.java:33)

Redis分片(Jedis)

Redis的分片技术一般是通过客户端或代理来实现的

1、用jedis实现分片的时候,服务端不需要做任何配置即可

package com.djhu.redis.test;

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

import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;

public class JedisShardTest
{
	public static void main(String[] args)
	{
		List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo>();
		jedisShardInfoList.add(new JedisShardInfo("172.16.172.4", 6379));
		jedisShardInfoList.add(new JedisShardInfo("172.16.172.4", 6380));

		ShardedJedis sharded = new ShardedJedis(jedisShardInfoList);
		sharded.set("key01", "a");
		sharded.set("key02", "b");
		sharded.set("key03", "c");
		sharded.set("key04", "d");
		sharded.set("key05", "e");
		
		System.out.println(sharded.get("key03"));
	}
}

2、用Jedis连接池实现分片

package com.djhu.redis.test;

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

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

public class JedisSharedFactory
{
	// 最大可用连接数,默认值为8,如果赋值为-1则表示不限制
	private static int MAX_TOTAL = 256;
	// 最大空闲连接数,默认值为8
	private static int MAX_IDLE = 32;
	// 最小空闲连接数
	private static int MIN_IDLE = 4;
	// 最大等待连接毫秒数,默认值为-1表示永不超时
	private static int MAX_WAIT = 3000;
	// 连接redis超时时间
	private static int TIMEOUT = 3000;
	// true表示验证连接
	private static boolean TEST_ON_BORROW = true;

	//连接池
	private static ShardedJedisPool jedisPool = null;
	public static void initJedisPool()
	{
		try
		{
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(MAX_TOTAL);
			config.setMaxIdle(MAX_IDLE);
			config.setMinIdle(MIN_IDLE);
			config.setMaxWaitMillis(MAX_WAIT);
			config.setTestOnBorrow(TEST_ON_BORROW);
			
			List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo>();
			jedisShardInfoList.add(new JedisShardInfo("172.16.172.4", 6379));
			jedisShardInfoList.add(new JedisShardInfo("172.16.172.4", 6380));
			jedisPool = new ShardedJedisPool(config, jedisShardInfoList,Hashing.MURMUR_HASH,Sharded.DEFAULT_KEY_TAG_PATTERN);
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public synchronized static ShardedJedis getConnection()
	{
		try
		{
			if (jedisPool != null)
			{
				ShardedJedis resource = jedisPool.getResource();
				return resource;
			} else
			{
				return null;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public static void returnResource(final ShardedJedis jedis)
	{
		if (jedis != null)
		{
			jedis.close();
		}
	}
	
	public static void main(String[] args)
	{
		initJedisPool();
		ShardedJedis redis = getConnection();
		redis.set("key10", "j");
		redis.set("key11", "k");
		redis.set("key12", "l");
		redis.set("key13", "m");
		redis.set("key14", "n");
		
		System.out.print(redis.get("key12"));
		
		returnResource(redis);
	}
}

Jedis连接Redis3 Cluster

1、源码如下

package com.djhu.redis.test;

import java.util.Set;
import java.util.HashSet;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

public class JedisClusterTest
{
	public static void main(String[] args)
	{
		Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();  
        jedisClusterNodes.add(new HostAndPort("172.16.172.4", 6379));  
        jedisClusterNodes.add(new HostAndPort("172.16.172.4", 6380));  
        jedisClusterNodes.add(new HostAndPort("172.16.172.4", 6381));  
        jedisClusterNodes.add(new HostAndPort("172.16.172.4", 6382));  
        jedisClusterNodes.add(new HostAndPort("172.16.172.4", 6383));  
        jedisClusterNodes.add(new HostAndPort("172.16.172.4", 7384));  
        
		//JedisCluster cluster = new JedisCluster(jedisClusterNodes,3000,1000);
        JedisCluster cluster = new JedisCluster(jedisClusterNodes);
		cluster.set("key10", "j");
		cluster.set("key11", "k");
		cluster.set("key12", "l");
		cluster.set("key13", "m");
		cluster.set("key14", "n");
		
		System.out.println(cluster.get("key12"));
		
	}
}

2、如果遇到下面错误,主要是因为建立cluster时,ip用了127.0.0.1。用其他ip重建一下cluster,就可以解决了。

Exception in thread "main" redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException: Too many Cluster redirections?
	at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:34)
	at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:68)
	at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:85)
	at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:68)
	at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:85)
	at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:68)
	at redis.clients.jedis.JedisClusterCommand.run(JedisClusterCommand.java:29)
	at redis.clients.jedis.JedisCluster.set(JedisCluster.java:75)

Jedis使用连接池(Java)

package com.djhu.redis.test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisFactory
{
	// 最大可用连接数,默认值为8,如果赋值为-1则表示不限制
	private static int MAX_TOTAL = 256;
	// 最大空闲连接数,默认值为8
	private static int MAX_IDLE = 32;
	// 最小空闲连接数
	private static int MIN_IDLE = 4;
	// 最大等待连接毫秒数,默认值为-1表示永不超时
	private static int MAX_WAIT = 3000;
	// 连接redis超时时间
	private static int TIMEOUT = 3000;
	// true表示验证连接
	private static boolean TEST_ON_BORROW = true;

	//连接池
	private static JedisPool jedisPool = null;
	public static void initJedisPool(String IP, int port, String password)
	{
		try
		{
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(MAX_TOTAL);
			config.setMaxIdle(MAX_IDLE);
			config.setMinIdle(MIN_IDLE);
			config.setMaxWaitMillis(MAX_WAIT);
			config.setTestOnBorrow(TEST_ON_BORROW);
			
			jedisPool = new JedisPool(config, IP, port, TIMEOUT, password);
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public synchronized static Jedis getConnection()
	{
		try
		{
			if (jedisPool != null)
			{
				Jedis resource = jedisPool.getResource();
				return resource;
			} else
			{
				return null;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public static void returnResource(final Jedis jedis)
	{
		if (jedis != null)
		{
			jedis.close();
		}
	}
	
	public static void main(String[] args)
	{
		initJedisPool("localhost",6379,null);
		Jedis redis = getConnection();
		redis.select(1);
		//redis.set("key01", "a");
		//redis.set("key02", "b");
		//redis.set("key03", "c");
		System.out.print(redis.dbSize());
		
		returnResource(redis);
	}
}

Redis入门之增删改查(Java)

1、下载驱动
jedis驱动源码地址
jedis驱动下载地址

2、测试代码

package com.djhu.redis.test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import redis.clients.jedis.Jedis;

public class ConnectionTest
{
	public static Jedis getConnection(String ip, int port)
	{
		Jedis jedis = new Jedis(ip, port);
		//jedis.auth("password");
		return jedis;
	}

	public static void cleanAll(Jedis jedis)
	{
		jedis.flushDB();
	}

	public static void stringTest(Jedis jedis)
	{
		jedis.set("key01", "a");
		jedis.set("key02", "b");
		jedis.set("key03", "c");
		jedis.mset("key04", "d", "key05", "e", "key06", "f");

		jedis.del("key04");
		System.out.println("key01 is " + jedis.get("key01"));
		System.out.println("key04 is " + jedis.get("key04"));
	}

	public static void mapTest(Jedis jedis)
	{
		Map<String, String> map = new HashMap<String, String>();
		map.put("username", "hansen");
		map.put("usersex", "male");
		jedis.hmset("mapkey01", map);

		map.put("username", "neohope");
		map.put("usersex", "male");
		jedis.hmset("mapkey02", map);

		map.put("username", "tuzi");
		map.put("usersex", "female");
		jedis.hmset("mapkey03", map);

		List<String> rsmap = jedis.hmget("mapkey03", "username", "usersex");
		System.out.println("query for hmget(\"mapkey03\", \"username\", \"usersex\") is " + rsmap);

		jedis.hdel("mapkey02", "usersex");
		System.out.println("query for hmget jedis.hmget(\"mapkey02\", \"username\") is "+jedis.hmget("mapkey02", "username"));
		System.out.println("query for jedis.hmget(\"mapkey02\", \"usersex\") is " + jedis.hmget("mapkey02", "usersex"));

		System.out.println("query for jedis.hlen(\"mapkey01\") is " + jedis.hlen("mapkey01"));
		System.out.println("query for jedis.exists(\"mapkey01\") is " + jedis.exists("mapkey01"));
		System.out.println("query for jedis.hkeys(\"mapkey01\") is " + jedis.hkeys("mapkey01"));
		System.out.println("query for jedis.hvals(\"mapkey01\") is " + jedis.hvals("mapkey01"));
	}

	public static void listTest(Jedis jedis)
	{
		jedis.lpush("keylist01", "a");
		jedis.lpush("keylist01", "b");
		jedis.lpush("keylist01", "c");

		System.out.println("keylist01 is " + jedis.lrange("keylist01", 0, -1));
	}

	public static void setTest(Jedis jedis)
	{
		jedis.sadd("keyset01", "01");
		jedis.sadd("keyset01", "02");
		jedis.sadd("keyset01", "03");
		jedis.sadd("keyset01", "04");
		jedis.sadd("keyset01", "05");

		System.out.println("query for jedis.smembers(\"keyset01\") is " + jedis.smembers("keyset01"));
		System.out.println("query for jedis.sismember(\"keyset01\", \"06\") is " + jedis.sismember("keyset01", "06"));
		System.out.println("query for jedis.scard(\"keyset01\") is " + jedis.scard("keyset01"));
	}

	public static void sortTest(Jedis jedis)
	{
		jedis.rpush("keylist02", "16");
		jedis.lpush("keylist02", "8");
		jedis.lpush("keylist02", "4");
		jedis.lpush("keylist02", "2");
		jedis.lpush("keylist02", "1");
		System.out.println("keylist02 is " + jedis.lrange("keylist02", 0, -1));
		jedis.sort("keylist02");
		System.out.println("after sort keylist02 is " + jedis.lrange("keylist02", 0, -1));
	}

	public static void main(String[] args)
	{
		Jedis jedis = getConnection("localhost", 6379);

		cleanAll(jedis);
		stringTest(jedis);
		mapTest(jedis);
		listTest(jedis);
		sortTest(jedis);
		setTest(jedis);
		jedis.close();
	}
}

Hadoop增删改查(Java)

需要的jar包在hadoop里都可以找到,下面的例子中,至少需要这些jar包:

commons-cli-1.2.jar
commons-collections-3.2.1.jar
commons-configuration-1.6.jar
commons-io-2.4.jar
commons-lang-2.6.jar
commons-logging-1.1.3.jar
guava-11.0.2.jar
hadoop-auth-2.7.1.jar
hadoop-common-2.7.1.jar
hadoop-hdfs-2.7.1.jar
htrace-core-3.1.0-incubating.jar
log4j-1.2.17.jar
protobuf-java-2.5.0.jar
servlet-api.jar
slf4j-api-1.7.10.jar
slf4j-log4j12-1.7.10.jar

代码如下:

package com.neohope.hadoop.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class HDFSTest {

	static Configuration hdfsConfig;
	static {
		hdfsConfig = new Configuration();
		hdfsConfig.addResource(new Path("etc/hadoop/core-site.xml"));
		hdfsConfig.addResource(new Path("etc/hadoop/hdfs-site.xml"));
	}

	// 创建文件夹
	public static void createDirectory(String dirPath) throws IOException {
		FileSystem fs = FileSystem.get(hdfsConfig);
		Path p = new Path(dirPath);
		try {
			fs.mkdirs(p);
		} finally {
			fs.close();
		}
	}

	// 删除文件夹
	public static void deleteDirectory(String dirPath) throws IOException {
		FileSystem fs = FileSystem.get(hdfsConfig);
		Path p = new Path(dirPath);
		try {
			fs.deleteOnExit(p);
		} finally {
			fs.close();
		}
	}

	// 重命名文件夹
	public static void renameDirectory(String oldDirPath, String newDirPath)
			throws IOException {
		renameFile(oldDirPath, newDirPath);
	}

	// 枚举文件
	public static void listFiles(String dirPath) throws IOException {
		FileSystem hdfs = FileSystem.get(hdfsConfig);
		Path listf = new Path(dirPath);
		try {
			FileStatus statuslist[] = hdfs.listStatus(listf);
			for (FileStatus status : statuslist) {
				System.out.println(status.getPath().toString());
			}
		} finally {
			hdfs.close();
		}
	}

	// 新建文件
	public static void createFile(String filePath) throws IOException {
		FileSystem fs = FileSystem.get(hdfsConfig);
		Path p = new Path(filePath);
		try {
			fs.createNewFile(p);
		} finally {
			fs.close();
		}
	}

	// 删除文件
	public static void deleteFile(String filePath) throws IOException {
		FileSystem fs = FileSystem.get(hdfsConfig);
		Path p = new Path(filePath);
		try {
			fs.deleteOnExit(p);
		} finally {
			fs.close();
		}
	}

	// 重命名文件
	public static void renameFile(String oldFilePath, String newFilePath)
			throws IOException {
		FileSystem fs = FileSystem.get(hdfsConfig);
		Path oldPath = new Path(oldFilePath);
		Path newPath = new Path(newFilePath);
		try {
			fs.rename(oldPath, newPath);
		} finally {
			fs.close();
		}
	}

	// 上传文件
	public static void putFile(String locaPath, String hdfsPath)
			throws IOException {
		FileSystem fs = FileSystem.get(hdfsConfig);
		Path src = new Path(locaPath);
		Path dst = new Path(hdfsPath);
		try {
			fs.copyFromLocalFile(src, dst);
		} finally {
			fs.close();
		}
	}

	// 取回文件
	public static void getFile(String hdfsPath, String locaPath)
			throws IOException {
		FileSystem fs = FileSystem.get(hdfsConfig);
		Path src = new Path(hdfsPath);
		Path dst = new Path(locaPath);
		try {
			fs.copyToLocalFile(false, src, dst, true);
		} finally {
			fs.close();
		}
	}

	// 读取文件
	public static void readFile(String hdfsPath) throws IOException {
		FileSystem hdfs = FileSystem.get(hdfsConfig);
		Path filePath = new Path(hdfsPath);

		InputStream in = null;
		BufferedReader buff = null;
		try {
			in = hdfs.open(filePath);
			buff = new BufferedReader(new InputStreamReader(in));
			String str = null;
			while ((str = buff.readLine()) != null) {
				System.out.println(str);
			}
		} finally {
			buff.close();
			in.close();
			hdfs.close();
		}
	}

	public static void main(String[] args) throws IOException {
		System.setProperty("HADOOP_USER_NAME", "hadoop");
		// createDirectory("hdfs://hadoop-master:9000/usr");
		// createDirectory("hdfs://hadoop-master:9000/usr/hansen");
		// createDirectory("hdfs://hadoop-master:9000/usr/hansen/test");
		// renameDirectory("hdfs://hadoop-master:9000/usr/hansen/test","hdfs://hadoop-master:9000/usr/hansen/test01");
		// createFile("hdfs://hadoop-master:9000/usr/hansen/test01/hello.txt");
		// renameFile("hdfs://hadoop-master:9000/usr/hansen/test01/hello.txt","hdfs://hadoop-master:9000/usr/hansen/test01/hello01.txt");
		// putFile("hello.txt","hdfs://hadoop-master:9000/usr/hansen/test01/hello02.txt");
		// getFile("hdfs://hadoop-master:9000/usr/hansen/test01/hello02.txt","hello02.txt");
		// readFile("hdfs://hadoop-master:9000/usr/hansen/test01/hello02.txt");
		listFiles("hdfs://hadoop-master:9000/usr/hansen/test01/");
	}

}

Xcode7文档下载地址

具体的下载地址,可以在这里查到
https://developer.apple.com/library/downloads/docset-index.dvtdownloadableindex

对于Xcode7,对应文档的下载地址为
watchOS 2.0 Documentation
iOS 9.0 Documentation
OS X 10.11 Documentation
Xcode 7 Documentation

已知问题
1、文档下载安装后可以使用,但Xcode无法识别。
2、从apple官网下,还是太慢了

Prolog求解Sudoku(七周七语言版本)

1、代码实现

:- use_module(library(clpfd)).
:- use_module(library(lists)).

%求解函数
sudoku(Puzzle, Solution) :-
  length(Puzzle, L),                         
  Size is floor(sqrt(L)),                    %计算矩阵大小                   
  Solution = Puzzle,
  Puzzle ins 1..Size,                        %输入必须符合规范(比如9阶Sudoku,元素必须在1到9之间)
  slice(Puzzle, Rows, Size, 'row'),          %将输入拆分为行,
  slice(Puzzle, Cols, Size, 'col'),          %列,
  slice(Puzzle, Squares, Size, 'square'),    %方格。
  valid(Rows),                               %每行,每列,每个方格不可重复
  valid(Cols),
  valid(Squares),
  pretty_print(Rows).                        %输出

%校验,一个List不可重复
valid([]).
valid([Head | Tail]) :- all_different(Head), valid(Tail).

%List截取
sublist_length([], _).
sublist_length([Head | Tail], Length) :- length(Head, Length), sublist_length(Tail, Length).

%List拼接
insert_into_slice(Item, Values, X, Y) :-
  nth0(X, Values, Bucket),
  nth0(Y, Bucket, Item).

%按行分割坐标
slice_position('row', Size, I, X, Y) :-   
  X is I // Size,
  Y is I mod Size.

%按列分割坐标
slice_position('col', Size, I, X, Y) :- 
  X is I mod Size,
  Y is I // Size.

%按方格分割坐标
slice_position('square', Size, I, X, Y) :- 
  Size_Sqrt is floor(sqrt(Size)),
  X is (I mod Size // Size_Sqrt) + (Size_Sqrt * (I // (Size * Size_Sqrt))),
  Y is (I mod Size_Sqrt) + (Size_Sqrt * ((I mod (Size * Size_Sqrt)) // Size)).

%数据分割函数
slice(Puzzle, Slice, Size, Type) :- slice(Puzzle, Slice, Size, Type, 0).
slice(_, Slice, Size, _, I) :- I is Size * Size, length(Slice, Size), sublist_length(Slice, Size).
slice([Head | Tail], Slice, Size, Type, I) :-
  slice_position(Type, Size, I, X, Y), 
  insert_into_slice(Head, Slice, X, Y),
  I1 is I + 1,
  slice(Tail, Slice, Size, Type, I1).

%输出函数
pretty_print([Head | Tail]) :-
  print(Head),
  nl,
  pretty_print(Tail).

2、测试一下

1 ?- sudoku([5, 3, _, _, 7, _, _, _, _, 
             6, _, _, 1, 9, 5, _, _, _, 
             _, 9, 8, _, _, _, _, 6, _, 
             8, _, _, _, 6, _, _, _, 3,
             4, _, _, 8, _, 3, _, _, 1,
             7, _, _, _, 2, _, _, _, 6,
             _, 6, _, _, _, _, 2, 8, _,
             _, _, _, 4, 1, 9, _, _, 5,
             _, _, _, _, 8, _, _, 7, 9], 
             Solution).

[5,3,4,6,7,8,9,1,2]
[6,7,2,1,9,5,3,4,8]
[1,9,8,3,4,2,5,6,7]
[8,5,9,7,6,1,4,2,3]
[4,2,6,8,5,3,7,9,1]
[7,1,3,9,2,4,8,5,6]
[9,6,1,5,3,7,2,8,4]
[2,8,7,4,1,9,6,3,5]
[3,4,5,2,8,6,1,7,9]
false.