八后问题Ruby01

Queen.rb

class Queen
  
  def initialize()
    @v=0
  end
  
  def arrCopy2(arr)
    arr0=Array.new(arr.length)
    for i in 0..arr.length-1 do
      arr0[i]=Array.new(arr[i])
    end
    
    return arr0
  end
  
  def addQueen(arr,x,y)
    setQueen(arr,x,y,1)
  end
  
  def setQueen(arr,x,y,n)
    for i in 0..arr.length-1 do
      arr[x][i]=n
    end
    
    for j in 0..arr[x].length-1 do
      arr[j][y]=n
    end 
    
    x0=x
    y0=y
    while x0<arr.length and y0<arr&#91;x0&#93;.length
      arr&#91;x0&#93;&#91;y0&#93;=n
      x0=x0+1
      y0=y0+1
    end
    
    x0=x
    y0=y
    while x0>=0 and y0>=0
      arr[x0][y0]=n
      x0=x0-1
      y0=y0-1
    end
    
    x0=x
    y0=y
    while x0>=0 and y0<arr&#91;x0&#93;.length
      arr&#91;x0&#93;&#91;y0&#93;=n
      x0=x0-1
      y0=y0+1
    end
    
    x0=x
    y0=y
    while x0<arr.length and y0>=0
      arr[x0][y0]=n
      x0=x0+1
      y0=y0-1
    end
    
    return arr
  end
  
  def findQueen(arr,lst,x) 
    
    if(x>=arr.length)
      @v=@v+1
      puts("]>>solution No."+@v.to_s)
      pp lst
      return
    end
    
    for y in 0..arr[x].length-1 do
      if(arr[x][y]==0)
        lst.push(y)
        arr0=arrCopy2(arr)
        addQueen(arr,x,y)   
        findQueen(arr,lst,x+1)
        arr=arr0
        lst.pop
      end
    end
     
  end
  
end

test.rb

require "pp"
require "./Queen.rb"

len = 8
arr=Array.new(len){Array.new(len, 0)}
#fuck
#arr = Array.new(len, Array.new(len,0))

lst = Array.new()

q=Queen.new
q.findQueen(arr,lst,0)

puts("end")

JAVA常用缩写

今天整理的一份文档,希望对大家有所帮助

AAA: Authentication, Authorization, Accounting

AWT: Abstract Window Toolkit (AWT VS. Swing VS. SWT)

AOP: ASPect Oriented Programming

BMP: Bean-Managed Persistent

CMP: Container-Managed Persistent

CORBA: Common Object Request Broker Architecture

DI: Dependency Injection

DTD: Document Type Definition

EJB: Enterprise Java Beans(Session Beans, Entity Beans, Message-driven Beans)

IDL: Interface Definition Language

IIOP: Internet Inter-ORB Protocol

IOC: Inversion Of Control

I18N: InternationalizationN

L10N: LocalizatioN

J2EE: Java2 Enterprise Edition(EJB, JTA, JDBC, JCA, JMX, JNDI, JMS, JavaMail, Servlet, JSP)

J2ME: Java2 Micro Edition

J2SE: Java2 Standard Edition

JAF: Java Action FrameWork

JCA: Java Cryptography Architecture

JCP: Java Community Process

JDBC: Java Data Base Connectivity

JDK: Java Development Kit

JDO: Java Data Object

JFC: Java Foundation Classes

JMS: Java Message Service

JNDI: Java Naming And Directory Interface

JNI: Java Native Interface

JPA: Java Persistence API

JRE: Java Runtime Environment

JSDK: Java Software Development Kit

JSF: Java Server Faces

JSP: Java Server Pages

JTA: Java Transaction API

JTS: Java Transaction Service

JVM: Java Virtual Machine(JRE VS. JNode VS. SableVM)

MVC: Model, View, Controller

OMG: Object Menagement Group

OCP: Open Closed Principle (Software entities should be open for extension, but closed for modification.)

OR Mapping: Object Relation Mapping

PI: Processing Instruction

PO: Persisent Object

POJO: Plain Ordinary Java Object

RADIUS: Remote Authentication Dial In User Service

RMI: Remote Method Invocation

RTTI: RunTime Type Identification

SOA: Service-Oriented Architecture

SPI: Service Provider Interface

WFC: Windows Foundation Classes for Java

WORA: Write Once, Run Anywhere

Io自学笔记01

//animal
animal := Object clone
animal name := "name"

//dog
dog := animal clone
dog name := "dog"
dog isSit := false
dog bark := method(writeln("woof"))
dog sit := method(
	if(isSit==true,writeln("sitting now");bark;return;)
	isSit=true
	writeln("sit ok")
	bark
)

//fido
fido := dog clone
fido name := "fido"
fido bark := method(
	writeln("ruf")
)

//test
writeln("dog bark>>")
dog bark
writeln("dog sit>>")
dog sit
writeln("dog sit>>")
dog sit

writeln("fido bark>>")
fido bark
writeln("fido sit>>")
fido sit
writeln("fido sit>>")
fido sit

JNI简单例子2

最近又用jni写了一个编码工具,从中抽出了最简单的代码,如下:

1、Compress4j.java

package com.neohope.test.compress.jni;

/**
 *
 * @author Hansen
 */
public class Compress4j {
    private native int encodeR(String inFilePath,String outFilePaht);
    private native int decodeR(String inFilePath,String outFilePaht);
    
    static{
        try{
            System.loadLibrary("compress4j");
        }catch(UnsatisfiedLinkError e){
            //nothing to do
            System.out.println("Error: Couldn't load compress4j");
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    
    public String encode(String inFilePath,String outFilePath)
    {
        encodeR(inFilePath, outFilePath);
        return "xxxxx";
    }
    
    public String decode(String inFilePath,String outFilePath)
    {
        decodeR(inFilePath, outFilePath);
        return "xxxxx";
    }
}

2、找到生成的classes文件夹,运行命令行:

javah -classpath . -jni com.neohope.test.compress.jni.Compress4j 

3、生成的.h文件如下

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_neohoe_test_compress_jni_Compress4j */

#ifndef _Included_com_neohoe_test_compress_jni_Compress4j
#define _Included_com_neohoe_test_compress_jni_Compress4j
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_neohoe_test_compress_jni_Compress4j
 * Method:    encodeR
 * Signature: (Ljava/lang/String;Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_com_neohoe_test_compress_jni_Compress4j_encodeR
  (JNIEnv *, jobject, jstring, jstring);

/*
 * Class:     com_neohoe_test_compress_jni_Compress4j
 * Method:    decodeR
 * Signature: (Ljava/lang/String;Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_com_neohoe_test_compress_jni_Compress4j_decodeR
  (JNIEnv *, jobject, jstring, jstring);

#ifdef __cplusplus
}
#endif
#endif

3、编写成的.cc文件如下

#include "com_neohoe_test_compress_jni_Compress4j.h"

JNIEXPORT jint JNICALL Java_com_neohoe_test_compress_jni_Compress4j_encodeR
  (JNIEnv *env, jobject, jstring inpathjs, jstring outpathjs)
{
    //first convert jstring to const char*
    const char* inpath = env->GetStringUTFChars( inpathjs, false);
    const char* outpath = env->GetStringUTFChars( outpathjs, false);

    //...

    return 0;
}

JNIEXPORT jint JNICALL Java_com_neohoe_test_compress_jni_Compress4j_decodeR
  (JNIEnv *env, jobject, jstring inpathjs, jstring outpathjs)
{
    //first convert jstring to const char*
    const char* inpath = env->GetStringUTFChars( inpathjs, false);
    const char* outpath = env->GetStringUTFChars( outpathjs, false);

    //...

    return 0;
}

4、在VS工程中,新增头文件目录
%JAVA_HOME%/include
%JAVA_HOME%/include/win32

5、编译为dll即可使用啦

6、关于mt和md的问题
编译为MT和MTd的话,用JNI是没有任何问题的
编译为MD的话,需要安装VC2010sp1可再发行包
编译为MDd的话,就比较麻烦了,手动复制依赖的dll后,我用c++调用dll可以成功,但用jni就一直提示:缺少依赖的dll

ipa包重签名

如果ipa打包时,签名文件不包括你的设备id,用itunes安装后是无法使用的,
这样,就要重新申请包含你设备id的证书,用下面的方法重签名:

1、把ipa和新证书放到同一目录下

2、新建文件resignipa.sh

IPA="xx.ipa"
IPAOUT="xxx.ipa"
PROVISION="xxxx.mobileprovision"
CERTIFICATE="xxxxx" # must be in keychain

# unzip the ipa
unzip -q "$IPA"

# remove the signature
rm -rf Payload/*.app/_CodeSignature Payload/*.app/CodeResources

# replace the provision
cp "$PROVISION" Payload/*.app/embedded.mobileprovision

# sign with the new certificate
/usr/bin/codesign -f -s "$CERTIFICATE" --resource-rules Payload/*.app/ResourceRules.plist Payload/*.app

# zip it back up
zip -qr "$IPAOUT" Payload

3、启动命令行

chmod 777 resignipa.sh
./resignipa.sh

生成IPA包

生成ipa包有以下几种方式:
1、自己手工打包
a、找到xcode生成app包
b、新建文件夹Payload,并把app包放进去
c、(可选)准备一张jpeg格式的图(<500*500px),用来显示在iTunes中 d、(可选)命名这张图为iTunesArtwork(无扩展名),并把它放在和Payload同一级目录中 e、将Payload和iTunesArtwork压缩,后缀名改为ipa即可 2、利用itunes a、找到xcode生成app包 b、直接拖到itunes中 c、在itunes的app目录下找到对应ipa即可(无图片) 3、利用xcode a、生成Archive b、在organizer的Archive界面选择share

go语言channel测试

go语言channel测试,请注意空格

package main
import "fmt"

const num_go_routine = 10000

func channeltest(left,right chan int){
	left<-1+<-right;
}

func main(){
	leftmost := make(chan int);

	var left,right chan int = nil,leftmost;
	for i:=0; i<num_go_routine; i++ {
		left, right = right, make(chan int);
		go channeltest(left,right);
	}

	right<-0;
	x := <-leftmost;
	fmt.Println(x);
}

注:本示例程序来自于《代码的未来》,松本行弘

Java摘要算法

package com.neohope.utils;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class NDigest
{
	/**
	 * Bytes to Hex String
	 * 
	 * @param hexBytes
	 * 
	 * @return hex string
	 */
	private static String bytesToHexString(byte[] hexBytes)
	{
		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < hexBytes.length; i++)
		{
			if ((hexBytes[i] & 0xff) < 0x10)
			{
				buf.append("0");
			}

			buf.append(Long.toString(hexBytes[i] & 0xff, 16));
		}

		return buf.toString();
	}

	/**
	 * calc MD5 for string
	 * 
	 * @param textIn
	 * 
	 * @return md5 digest string
	 * @throws NoSuchAlgorithmException
	 */
	public static String MD5Digest(String textIn)
			throws NoSuchAlgorithmException
	{
		byte[] textData = textIn.getBytes();

		MessageDigest md = null;
		md = MessageDigest.getInstance("MD5");
		md.reset();
		md.update(textData);

		byte[] encodedData = md.digest();
		return bytesToHexString(encodedData);
	}

	/**
	 * calc SHA1 for string
	 * 
	 * @param textIn
	 * 
	 * @return sha1 digest string
	 * @throws NoSuchAlgorithmException
	 */
	public static String SHA1Digest(String textIn)
			throws NoSuchAlgorithmException
	{
		byte[] textData = textIn.getBytes();

		MessageDigest md = null;
		md = MessageDigest.getInstance("SHA1");
		md.reset();
		md.update(textData);

		byte[] encodedData = md.digest();
		return bytesToHexString(encodedData);
	}

	/**
	 * Encode a string using Base64 encoding.
	 * 
	 * @param textIn
	 * @return String
	 */
	public static String base64Encode(String textIn)
	{
		sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
		return encoder.encodeBuffer(textIn.getBytes()).trim();
	}

	/**
	 * Decode a string using Base64 encoding.
	 * 
	 * @param textIn
	 * @return String
	 * @throws IOException
	 */
	public static String decodeString(String textIn) throws IOException
	{
		sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
		return new String(dec.decodeBuffer(textIn));
	}

	/**
	 * 使用 HMAC-SHA-1 签名方法对对textIn进行摘要
	 * 
	 * @param textIn
	 * @param keyIn
	 * @return
	 * @throws Exception
	 */
	public static String HmacSHA1Digest(String textIn, String keyIn)
			throws Exception
	{
		final String MAC_NAME = "HmacSHA1";
		final String ENCODING = "UTF-8";

		byte[] keyData = keyIn.getBytes(ENCODING);
		SecretKey secretKey = new SecretKeySpec(keyData, MAC_NAME);
		Mac mac = Mac.getInstance(MAC_NAME);
		mac.init(secretKey);

		byte[] textData = textIn.getBytes(ENCODING);
		byte[] encodedData = mac.doFinal(textData);

		return bytesToHexString(encodedData);
	}

	// 我就是那个测试函数。。。
	public static void main(String args[]) throws Exception
	{
		String key = "Y9zTQxRvxwrHOi45OoKNnIoxboerNqt3";
		String text = "Good good study, day day up.";
		String hmacSHA1 = HmacSHA1Digest(text, key );
		String base64 = base64Encode(hmacSHA1);
		System.out.println(hmacSHA1 );
		System.out.println(cbase64);
	}
}

排序算法Ruby Part2

6、Heap sort 堆排序

  # Heap sort 堆排序
  # 使用堆进行排序,每次重建堆后,将堆顶元素放到堆数组最后,
  # 堆数组长度减一
  # Time Complexity: О(nlogn) average and worst-case
  # Space Complexity: О(n) total, O(1) auxiliary
  # Stable: Yes
  def heapsort(container)
    return container if container.size <= 1
    
    buildheap(container)
    size = container.size
    while size > 0
      container[0], container[size-1] = container[size-1], container[0]
      size = size - 1
      heapify(container, 0, size)
    end
    
    return container
  end
  
  private
  
  # 重建堆
  # 某节点及其所有子节点,符合最大堆的特性
  def heapify(container, idx, size)
    left_idx = 2 * idx + 1
    right_idx = 2 * idx + 2
    bigger_idx = idx
    bigger_idx = left_idx if left_idx < size && container[left_idx] > container[idx]
    bigger_idx = right_idx if right_idx < size && container[right_idx] > container[bigger_idx]
    if bigger_idx != idx
      container[idx], container[bigger_idx] = container[bigger_idx], container[idx]
      heapify(container, bigger_idx, size)
    end
    return container
  end
  
  # 初始化最大堆,堆顶元素为container[0]
  # 元素i的左节点为2*i+1,元素i的右节点为2*i+2
  def buildheap(container)
    last_parent_idx = container.length / 2 - 1
    i = last_parent_idx
    while i >= 0
      heapify(container, i, container.size)
      i = i - 1
    end
  end

7、Quicksort 快速排序

  # Quicksort 快速排序
  # 用分治法进行排序,充分利用了每次比较的结果,
  # 每次排序都将排序对象分成了两组,分别进行排序
  # Time Complexity: О(n log n) average, O(n^2) worst-case
  # Space Complexity: О(n) auxiliary
  # Stable: No
  def quicksort(container)
    return container if container.size<2

    i=0
    j=container.size-1
    key=container[i]

    while(i<j) do
      while(i<j and container[j]>key) do
        j=j-1
      end
      if(i<j)
        container[i]=container[j]
        i=i+1
      end

      while(i<j and container[i]<key) do
        i=i+1
      end
      if(i<j)
        container[j]=container[i]
        j=j-1
      end
    end
    container[i]=key
    
    f= 0<=i ? quicksort(container[0,i+1]): nil
    t= i<=container.size-1 ? quicksort(container[i+1,container.size-1]): nil

    return t if(f==nil)
    return f if(t==nil)
    return f+t
  end

8、Counting Sort 计数排序

  # Counting Sort 计数排序
  # 计算最小值和最大值,利用标志位来标记元素出现次数
  # Time Complexity: О(n+k) for best, average and worst-case
  # Space Complexity: О(n+k) auxiliary
  # Stable: Yes
  def countingsort(container)
    min = container.min
    max = container.max
    counts = Array.new(max-min+1, 0)

    container.each do |n|
      counts[n-min] += 1
    end

    j=0
    for i in 0..counts.size-1 do
      if(counts[i]!=0)
        while(counts[i]>0) do
          container[j] = min+i
          counts[i]-=1
          j+=1
        end
      end

      i+=1
    end

    return container
  end

9、Radix Sort 基数排序

  # Radix Sort 基数排序
  # 从个位数进行进行排序,一直到最高位
  # Time Complexity: О(k*n) for worst-case
  # Space Complexity: О(k+n) for worst-case
  # Stable: Yes
  def radixsort(container)
    
    max = container.max
    d = Math.log10(max).floor + 1

    (1..d).each do |i|
      radix = []
      (0..9).each do |j|
        radix[j] = []
      end

      container.each do |n|
        kth = calckth(n, i)
        radix[kth] << n
      end
      
      container = radix.flatten
    end

    return container
  end

  private
  
  def calckth(n, i)
    while(i > 1)
      n = n / 10
      i = i - 1
    end
    n % 10
  end

10、Bucket sort 桶排序

  # Bucket sort 桶排序
  # 将数组分到有限数量的桶里,每个桶再进行排序
  # Time Complexity: О(n) for best, О(n+k) for average, O(n^2) for worst-case
  # Space Complexity: О(n*k) for worst-case
  # Stable: Yes
  def bucketsort(container)
    bucket = []
    (0..9).each do |j|
      bucket[j] = []
    end
      
    container.each do |n|  
      k = getfirstnumber(n)
      bucket[k] << n
    end  
    
    (0..9).each do |j|  
      bucket[j] = quicksortB(bucket[j])  
    end
    
    bucket.flatten  
  end

  private
  
  #假设都是两位正整数
  def getfirstnumber(n)  
    m = n/10
    m=0 if m<0
    m=9 if m>9
    
    return m
  end
  
  def quicksortB(container)  
    (x=container.pop) ? quicksortB(container.select{|i| i <= x}) + [x] + quicksortB(container.select{|i| i > x}) : []  
  end