writing code to generate permutations of a string - hashset

I am looking to generate permutations and as part of the process,I wrote the following code using HashSet.
public static HashSet<String> getAllPermutations(String str)
{
// Create a hash set to prevent any duplicate entries
HashSet<String> permutations = new HashSet<String>();
if(str == null || str.length() == 0)
{
permutations.add("");
return permutations;
}
char first = str.charAt(0);
String remainingString = str.substring(1);
HashSet<String> words = getAllPermutations(remainingString);
System.out.println("here: "+ words.toString());
}
My question is that when I try to print out thenter code heree hashset "words" using the string abc in the main method, I get this output:
here: []
here: [c]
here: [bc, cb]
Why am I getting bc and cb both in my HashSet? Is there something about Hashsets I am missing here?

Related

How to seach emoji with proper text via Entity Framework Core

Here is my code:
var emoji = "⭐";
var query = myContext.Products.Where(x => x.Name.Contains(emoji));
var queryString = query.ToQueryString();
var list = query.ToList();
Query returns all table records. If I replace contains to equal works great, but I have to search something like this:
"this is my emoji ⭐"
This is the SQL query:
DECLARE #__emoji_0 nvarchar(4000) = N'⭐'
SELECT [p].[Id], [p].[Name], [p].[Quantity]
FROM [Products] AS [p]
WHERE (#__emoji_0 LIKE N'') OR (CHARINDEX(#__emoji_0, [p].[Name]) > 0)
Is any way to do this in EF Core or raw SQL?
Your main issue is the fact that emojis and strings are represented differently.
Before you can search the emojis you will need to decide how are you gonna unify them both in search query and db.
First of all emojis are a pair of chars.What does that mean? Here as a quote from the Microsoft docs:
"🐂".Length = 2
s[0] = '�' ('\ud83d')
s[1] = '�' ('\udc02')
These examples show that the value of string.Length, which indicates the number of char instances, doesn't necessarily indicate the number of displayed characters. A single char instance by itself doesn't necessarily represent a character.
The char pairs that map to a single character are called surrogate pairs. To understand how they work, you need to understand Unicode and UTF-16 encoding.
Having this in mind I would go as follows:
Define a method which will convert emojis to a UTF16 string[] which will keep the two surrogate chars representation.
internal static string[] EmojiToUtf16Pair(string emoji)
{
string[] arr = new string[2];
for (int i = 0; i < emoji.Length; i++)
{
arr[i] = emoji[i].ToString();
}
return arr;
}
This could be use when you persist emojis in DB. Depending on how you decide to persist the emojis in DB some modification could be done for that method e.g. to return concatenated string or something like that.
I am not sure when, but for some reason you could use another method to do the reverse operation -> UTF16 to Emoji
internal static string UTF16PairToEmoji(string[] codes)
{
var test = string.Empty;
foreach (var i in codes)
{
test += i;
}
var result = test.ToString();
return result;
}
Here is all the code example:
class Program
{
static void Main()
{
var str = "🚴";
var utf16 = string.Join("",EmojiToUtf16Pair(str));
Console.WriteLine(utf16);
var testEmpoji = UTF16PairToEmoji(EmojiToUtf16Pair(str));
Console.WriteLine(testEmpoji);
}
internal static string[] EmojiToUtf16Pair(string emoji)
{
string[] arr = new string[2];
for (int i = 0; i < emoji.Length; i++)
{
arr[i] = emoji[i].ToString();
}
return arr;
}
internal static string UTF16PairToEmoji(string[] codes)
{
var test = string.Empty;
foreach (var i in codes)
{
test += i;
}
var result = test.ToString();
return result;
}
}
emoji ef-core db-query
You have to use like command
SELECT * FROM emoticon where emoji_utf like '👨🏫';
with EF in .net core
Emoticon emoticon=db_context.Emoticons.Where(a=>EF.Functions.Like(a.EmojiUtf,"%"+item.emojiString+"%" ) ).FirstOrDefault();

How can I get whole string value from List in apex

I need your help.
I made an apex class which is giving output like (1,i,n,d,i,a,,1,2,3) and I would like to show output as a whole string format like(1india 123). I tried many different ways but couldn't get what I actually want.
Here is my apex class:-
public class Assign2{
public void testFunction(String str ,integer num){
integer rem,temp = 0;
integer sumOfDigit = 0;
List<String> stringCharacters = new List<String>();
List<String> inputStr = new List<String>();
stringCharacters = str.split('');
System.debug('stringCharacters::'+stringCharacters);
for(integer i=0; i<stringCharacters.size(); i++){
if(stringCharacters[i].isNumeric()){
temp = Integer.valueOf(stringCharacters[i]);
//System.debug('temp::'+temp);
rem = temp +num;
//System.debug('rem::'+rem);
sumOfDigit = math.mod(rem,10);
//System.debug('sumOfDigit::'+sumOfDigit);
stringCharacters[i] = sumOfDigit+'';
//System.debug('ans::'+stringCharacters);
}
}
System.debug('ans::'+stringCharacters);
}}
and I run the program by giving input:-
Assign2 obj = new Assign2();
obj.testFunction('2india 234',9);
help will be appreciable.
Thank You.
You've used split with empty string as parameter (meaning you want to cut it into 1-character strings). All you have to do is to reverse the process with join.
List<String> characters = new List<String>{'1','i','n','d','i','a',' ','1','2','3'};
String word = String.join(characters, '');
System.debug(word); // "1india 123"

Reaching from one string to another using given dictionary

For this question, a dictionary was given and two strings also given, it was basically asked to reach from one string to another one just using the words in dictionary, and only one letter can be changed at a time. I came up with this solution. There were some corner cases that my code can not handle. Can you help to find all the corner cases to make this code prettier?
public static int findNumberOfSteps(String start, String end , HashSet<String> dict){
if( start == null || end == null || dict.isEmpty()){
throw new IllegalArgumentException();
}
dict.add(end);
Queue<String> wordHolder = new LinkedList<>();
Queue<Integer> distanceCount = new LinkedList<Integer>();
wordHolder.add(start);
distanceCount.add(1);
int result = Integer.MAX_VALUE;
while (!wordHolder.isEmpty()){
String currentWord = wordHolder.poll();
int currDistance = distanceCount.poll();
if(currentWord.equals(end)){
int result = currDistance;
return result;
}
for (int i = 0 ; i < currentWord.length() ; i++){
char[] charCurrentWord = currentWord.toCharArray();
for ( char c = 'a' ; c <= 'z' ; c++){
charCurrentWord[i] = c;
String newWord = new String(charCurrentWord);
if (dict.contains(newWord)){
wordHolder.add(newWord);
distanceCount.add(currDistance+1);
dict.remove(newWord);
}
}
}
}
return 0;
}
There are a couple of problems in the code. The first problem is in this code
if(currentWord.equals(end)){
result = Math.min(result, currDistance);
}
Note that when you reach the end word, that code updates the result, but then the code is going to search for ways to change the end word to something else. That's a huge waste of time, the code should continue with the while(!wordHolder.isEmpy()) loop after the end is found.
The second problem is in this code
if (dict.contains(newWord)){
wordHolder.add(newWord);
distanceCount.add(currDistance+1);
dict.remove(newWord);
}
Note that if newWord is equal to the end word, then that code removes the end word from the dictionary, which means that you'll never find the end word again.
The solution to both problems is to check for the end word inside that if statement. When the end is found, don't add it to the wordHolder and don't remove it from the dictionary.
if (dict.contains(newWord)){
if(newWord.equals(end)){
result = Math.min(result, currDistance+1);
}
else{
wordHolder.add(newWord);
distanceCount.add(currDistance+1);
dict.remove(newWord);
}
}

How to match the Code of barcode with array codes?

I want a matching array has codes
I've match one code it works without a problem
this code is works well
let code = "code"
if metadataObj.stringValue == code {
println("the code is true")
}else {
println("the code is false")
}
But when I try this code
var codes = ["a","b","c"]
if metadataObj.stringValue == codes {
println("the code is true")
}else {
println("the code is false")
}
This problem appears
cannot invoke == with an argument list of type
It works well with array var codes = ["a","b","c"] But when you put array of analysis JSON local file is not working
A string cannot be equal to an array.
If you want to test if the string is equal to one of the array elements
then use contains():
if contains(codes, metadataObj.stringValue) { ... }

Search a Substring in a List<string>

I have a List of Codes (COD_XX) and I need to search each code in a text file, and get the index of the line where is located. The first caracter of the line contains the cod.
I've saved all the lines in a List
var fileLines = File.ReadAllLines(filePath);
List<string> fileItems = new List<string>(fileLines);
foreach (string param in lstCodes)
{
int idx = fileItems.FindIndex(m => m.Substring(0,6) == param)
}
But this expression is not working :( How should I writte it?
Thank you in advanced for your help.
Your code works fine if you put ; after fileItems.FindIndex(...)
But m.Substring(0,6) could throw an exception if m is shorter than 6.
You should use String.StartsWith method.
foreach (string param in lstCodes)
{
int idx = fileItems.FindIndex(m => m.StartsWith(param));
}

Resources