golang data structures and algorithms - the sparse array (Hanshun Ping explain)

  1. Sparse array sparesearray
  • When most of the elements in an array is 0, or a value of the same array, the sparse array can be used to hold the array

       Approach:

 1) Record the array, a total of several odd row, how many different values

 2) The ranks and the value of the recording element having different values ​​in an array of small, thereby downsizing the program

 

 Sparse array is a typical compression algorithm.

  • Write a backgammon program, save and exit and have continued function on the disk

 

  •  Code
  • main Package 
    
    Import "FMT" 
    
    FUNC main () { 
    
    	//. 1. to create an original array 
    	var chessMap [. 11] [. 11] int 
    	chessMap [. 1] [2] = //. 1 Black 
    	chessMap [2] [3] blue chess = 2 // 
    
    	// look at the second output of the original array 
    	for _, V: = {Range chessMap 
    		for _, V1: Range = V { 
    			fmt.Printf ( "% D \ T", V1) 
    		} 
    		FMT. println () 
    	} 
    
    	type struct {valNode 
             ARR int 
             COL int 
             Val int 
    	} 
    
    	valnode: = {valNode 
    		ARR:. 11, 
    		COL:. 11, 
    		Val: 0, 
    	} 
    	var SparseArray [] valNode 
    	SparseArray = the append (SparseArray, valnode) 
    	//. 3. converted into a sparse array 
    
    	for i, v: = range chessMap {
    		J for, V1: Range = V {  
    			IF V1 = {0!
    				valnode = {ValNode 
    					ARR: I, 
    					COL: J, 
    					Val: V1, 
    				} 
    				SparseArray = the append (SparseArray, valnode) 
    			} 
    		} 
    	} 
    
    	  fmt.Println ( "current sparse array is ::: : ") 
    	for I, V: = Range SparseArray { 
    		fmt.Printf ("% D%% D D D% \ n-", I, v.arr, v.col, v.val) 
    	} 
    		fmt.Println () 
    
    	/ / save 
    	read file is omitted // 
    
    	// restore the original array 
    	var chessMap2 [. 11] [. 11] int 
    
    	for I, valnode: = Range SparseArray { 
    
    		! IF I = {0 // skip the first row 
    			chessMap2 [valnode.arr ] [valnode.col] = valnode.val 
    		} 
    
    	} 
        fmt.Println ( "raw data recovery :::") 
    
    
    	for _, V: = {Range chessMap2 
    		for _, V1: Range = V { 
    			fmt.Printf ( "% D \ T", V1) 
    		}
    		fmt.Println()
    	}
    
    	}
    

      

Guess you like

Origin www.cnblogs.com/kdxx/p/12661489.html