Created
April 20, 2017 05:39
-
-
Save jianminchen/7a8fe479728f6d3a60ec2d6373c6f796 to your computer and use it in GitHub Desktop.
Recursive function practice - dictionary talk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Flat a ctionary | |
// key: string | |
// value is string, sometimes it is dictionary | |
// value '1' - string | |
// 'a': '2' key 'a' value string '2' | |
// 'c': key, value is Dictionary | |
// key1: 1 | |
// value, how can I determine that it is a string or dictionary | |
// Key2.a: '2' | |
// key2.b: '3' | |
// key is constructed by concatenated key2 -> DFS -> recursive function | |
// keystring prefix = empty string | |
// create new Dictionary <string, string> | |
// step 1: Dictionary -> keys -> iterate on the key | |
// step 2: for each key, value object -> Determine Runtime type -> string , Dictionary | |
// step 3: output the key value pair to new dictionary -> key, value is the same | |
// step 4: if value is Dictinary, continue step 1 -> pass into key string prefix | |
// return new dictionary <string, string> | |
using System; | |
class LearningExperience { | |
static void Main(string[] args) { | |
Console.WriteLine("Meet a talent and talk about algorithm"); | |
var data = new Dictionary<string, object>(); | |
data.Add('key1','1'); | |
data.Add('key2', new Dictionary<..>) | |
var flatten = new Dictionary<string, string>(); | |
var flattenOnes = FlatternDictionaryRecursive(data, flattern, string.emtpy); | |
} | |
/// key1: 1 | |
/// DFS -> overflow -> too deep -> iterative solution out-of-stack | |
// | |
public static void FlatternDictionaryRecursive(IDictionary<string, object> data, Dictionary<string, object> flattern, string prefix ) | |
{ | |
if(data == null || data.Count == 0) return; | |
foreach(string key in data.Keys) | |
{ | |
var current = data[key]; | |
var newKey = (prefix == null)? key : (prefix +'.' +key) ; | |
if(current.IsString()) | |
{ | |
flattern.Add(newKey, current); | |
} | |
else | |
{ | |
// it is a dictionary | |
prefix = newKey; // Key2 | |
FlatternDictionaryRecursive(current, falttern, prefix); | |
} | |
} | |
// do nothing | |
return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment