- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get all the combinations of the keypad value in a mobile by backtracking using C#?
The problem can be broken down into smaller and simple "subproblems", which can be further divided into yet simpler and smaller subproblems. We take each and every digit one by one and count all ndigits reachable from any digit, use a map to store the mapping of digits reachable from every digit. When the digit becomes n-digit, update the count.
Example
using System; using System.Collections.Generic; namespace ConsoleApplication{ public class BackTracking{ private string GetKeyPadValueBasedOnInput(string digit){ Dictionary keypad = new Dictionary(); keypad.Add("2", "abc"); keypad.Add("3", "def"); keypad.Add("4", "ghi"); keypad.Add("5", "jkl"); keypad.Add("6", "mno"); keypad.Add("7", "pqrs"); keypad.Add("8", "tuv"); keypad.Add("9", "wxyz"); return keypad.GetValueOrDefault(digit); } public void FindSequence(string currentList, string digits, List output){ if (digits.Length == 0){ output.Add(currentList); return; } else{ string digit = digits.Substring(0, 1); string letters = GetKeyPadValueBasedOnInput(digit); for (int i = 0; i < letters.Length; i++){ char letter = GetCHarFromString(letters, i); FindSequence(currentList + letter, digits.Substring(1), output); } } } private char GetCHarFromString(string letters, int value){ char[] charArr = letters.ToCharArray(); return charArr[value]; } } class Program{ static void Main(string[] args){ BackTracking b = new BackTracking(); List<string> output = new List<string>(); b.FindSequence("", "34", output); foreach (var item in output){ Console.WriteLine(item); } } } }
Output
dg dh di eg eh ei fg fh fi
Advertisements