programming logic problem - math

I need a function that can give me all possible combinations of a array back.
Example:
$source = array('a', 'b', 'c');
$target = thisiswhatisearch($source);
Now the $target should look like:
array('a','b','c','ab','ac','cb','abc')
I dont need the aa, bb, cc.
I also dont need the the ba, ca, acb.. because the order isn't important to me.
Thanks for any help.

Tried to be language agnostic but i guess its C like:
function combinations(array arr)
{
combos = array();
for (int i=1; i<2**arr.size(); i++)
{
int x = i;
int c = 0;
str = "";
while(x>0)
{
int rem = x % 2;
if(rem == 1)
str += arr[c];
x = x / 2;
c++;
}
combos.add(str);
}
return combos;
}

The Wikipedia entry for Combination has a link to C code that does this.

That's an out of the mind solution. It is probably not the fastest and cleanest one, but it kind of works. It's in Java, because I had it open:
public class Combination {
public static void main(String[] args) {
String[] source = {"a","b","c"};
List<String> result = combineMe(new ArrayList<String>(Arrays.asList(source)));
for (String string : result) {
System.out.println(string);
}
}
public static List<String> combineMe(List<String> source) {
List<String> result = new ArrayList<String>();
if (source.size()==0) {
result.add("");
return result;
}else{
String tmp = source.remove(0);
source = combineMe(source);
for (String string : source) {
result.add(("" + string).trim());
result.add(tmp + string);
}
}
return result;
}
}
The first entry in the resulting list is a fake one, and needs to be removed at the end

Related

netcore - elegant way to check var A or B is not null/empty to get it

Is there any operator like || to get first non-null/empty value like we can do in other languages?
I can achieve the same using ifs:
public static void Main(string[] args)
{
string a = "value";
string b = null;
string c = b;
if (string.IsNullOrEmpty(c)) {
c = a;
if(string.IsNullOrEmpty(c)){
throw new System.Exception("...");
}
}
}
If I have more variables to check, it will become a mess. Is there other way to achieve it?
You can use extensions for this
public static string IfNullOrEmptyGet(this string str, string newValue)
{
if (!string.IsNullOrEmpty(str))
return str;
if (string.IsNullOrEmpty(newValue))
throw new Exception($"{nameof(newValue)} is null or empty");
else
return newValue;
}
and use like c = c.IfNullOrEmptyGet(a)

Does Ref keyword useful for DataTable

I read DataTable are of Reference type, then does using ref keyword make any difference ? Are below two approaches same in terms of performance?
(1)
public int CalculateValues(DataTable dt)
{
int output = 0;
foreach(DataRow row in dt.Rows)
{
//CalculateValues
}
return output;
}
(2)
public int CalculateValues(ref DataTable dt)
{
int output = 0;
foreach(DataRow row in dt.Rows)
{
//CalculateValues
}
return output;
}
(1) vs (2) ?
When you pass value type to method, it's do copy your variable, but when you pass reference type it's copy pointer value.
Here is example.
public void Change(ReferenceType val)
{
val = new ReferenceType();
}
public void ChangeRef(ref ReferenceType val)
{
val = new ReferenceType();
}
void SomeFunction()
{
var variable = new ReferenceType();
var tmp = variable;
Change(variable); // variable not changed
Console.WriteLine(variable == tmp); // will print TRUE
ChangeRef(ref variable); // variable changed
Console.WriteLine(variable == tmp); // will print FALSE
}
So, it's not about performance at all.

Trouble with getting codes for Huffman Tree

I need to create the codes to compress a Huffman Tree. (O if you traverse left 1 if you traverse right.)
Right now the codes array will get the correct first code, but afterwards will only return null.
I am not allowed to use any instance/global variables or any predefined java classes besides array and arrayList
public static String compress(final BinaryNodeInterface<Character> root, final String message)
{
String[] codes;
ArrayList<Character> letter = new ArrayList<Character>();
String codeString = "";
boolean addChar=true;
for(int i =0; i<message.length();i++)
{
for(int j=0;j<letter.size();j++)
if(message.charAt(i)==letter.get(j))
addChar=false;
else
addChar=true;
if(addChar)
letter.add(message.charAt(i));
}
codes = new String[letter.size()];
for(int i=0;i<letter.size();i++)
codes[i]=(getPath(root,letter.get(i),""));
return ""; // Do not forget to change this line!!!
}
private static String getPath(final BinaryNodeInterface<Character> root, char toFind, String path)
{
String result;
if (! root.isLeaf()) {
if ((result = getPath(root.getLeftChild(),toFind, path + '0')) == null) {
result = getPath(root.getLeftChild(),toFind, path + '1');
}
}
else {
result = (toFind == root.getData()) ? path : null;
}
return result;
}
You don't seem to be visiting the right sub child. Change
result = getPath(root.getLeftChild(),toFind, path + '1');
to
result = getPath(root.getRightChild(),toFind, path + '1');

set control ID using string.concat

i've some code in c#, in which there are many lines of code where the ID of a control is set by string.concat. For ex:
private genericControl ctrlGrid;
genericControl = Page.LoadControl(obj);
genericControl.ID = string.concat("gridControl");
Can there be any specific reasons for setting the ID using string.concat?
Can there be any performance hit associated with this?
I think you should use just:
genericControl.ID = "gridControl";
EDIT:
Take a look at string.Concat() method that will be used when you are passing one parameter:
public static string Concat(params string[] values)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
int totalLength = 0;
string[] strArray = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
string str = values[i];
strArray[i] = (str == null) ? Empty : str;
totalLength += strArray[i].Length;
if (totalLength < 0)
{
throw new OutOfMemoryException();
}
}
return ConcatArray(strArray, totalLength);
}
So yes, it has performance overhead and better to use just string.

Use MatchPattern property of FindMatchingFiles workflow activity

I'm customizing the default workflow of build process template using TFS 2010 Team Build. There is an activity named FindMatchingFiles allows to search for specific files with a pattern defined in MatchPattern property. It works if I only specify one file extension. Example:
String.Format("{0}\\**\\\*.msi", SourcesDirectory)
But I would like to include *.exe as well. Trying following pattern but it doesn't work:
String.Format("{0}\\**\\\*.(msi|exe)", SourcesDirectory)
Anyone could show me how to correct it?
You can use String.Format("{0}\**\*.msi;{0}\**\*.exe", SourcesDirectory)
The FindMatchingFiles activity's MatchPattern property uses the
Syntax that is supported by the searchPattern argument of the Directory.GetFiles(String, String) method.
That means that you can't combine multiple extensions. You'll need to call the FindMatchingFiles activity twice. You can then combine the results of those two calls when you use them (i.e. if your results are msiFiles and exeFiles, you can use msiFiles.Concat(exeFiles) as the input to a ForEach).
However, as you can see with #antwoord's answer, the activity does actually seem to accept a semi-colon delimited list of patterns, unlike Directory.GetFiles.
FindMatchingFiles has some strange search pattern. Here is the code (decompiled using ILSpy) so you can test your search patterns without having to kick off a new build.
It contains a hardcoded root dir at the following location (Z:)
List<string> matchingDirectories = GetMatchingDirectories(#"Z:", matchPattern.Substring(0, num), 0);
Code:
using System;
using System.Collections.Generic;
using System.IO;
namespace DirectoryGetFiles
{
//// Use the FindMatchingFiles activity to find files. Specify the search criteria in the MatchPattern (String) property.
//// In this property, you can specify an argument that includes the following elements:
//// Syntax that is supported by the searchPattern argument of the Directory GetFiles(String, String) method.
////
//// ** to specify a recursive search. For example:
//// To search the sources directory for text files, you could specify something that resembles the following
//// value for the MatchPattern property: String.Format("{0}\**\*.txt", SourcesDirectory).
////
//// To search the sources directory for text files in one or more subdirectories that are called txtfiles,
//// you could specify something that resembles the following value for the MatchPattern property:
//// String.Format("{0}\**\txtfiles\*.txt", SourcesDirectory).
class Program
{
static void Main(string[] args)
{
string searchPattern = #"_PublishedWebsites\Web\Scripts\jasmine-specs**\*.js";
var results = Execute(searchPattern);
foreach (var i in results)
{
Console.WriteLine("found: {0}", i);
}
Console.WriteLine("Done...");
Console.ReadLine();
}
private static IEnumerable<string> Execute(string pattern)
{
string text = pattern;
text = text.Replace(";;", "\0");
var hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
string[] array = text.Split(new char[]
{
';'
}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < array.Length; i++)
{
string text2 = array[i];
string text3 = text2.Replace("\0", ";");
if (IsValidPattern(text3))
{
List<string> list = ComputeMatchingPaths(text3);
if (list.Count > 0)
{
using (List<string>.Enumerator enumerator = list.GetEnumerator())
{
while (enumerator.MoveNext())
{
string current = enumerator.Current;
hashSet.Add(current);
}
goto IL_15C;
}
}
////Message = ActivitiesResources.Format("NoMatchesForSearchPattern", new object[]
}
else
{
//// Message = ActivitiesResources.Format("InvalidSearchPattern", new object[]
}
IL_15C: ;
}
return hashSet;//.OrderBy((string x) => x, FileSpec.TopDownComparer);
}
private static bool IsValidPattern(string pattern)
{
string text = "**" + Path.DirectorySeparatorChar;
int num = pattern.IndexOf(text, StringComparison.Ordinal);
return (num < 0 || (pattern.IndexOf(text, num + text.Length, StringComparison.OrdinalIgnoreCase) <= 0 && pattern.IndexOf(Path.DirectorySeparatorChar, num + text.Length) <= 0)) && pattern[pattern.Length - 1] != Path.DirectorySeparatorChar;
}
private static List<string> ComputeMatchingPaths(string matchPattern)
{
List<string> list = new List<string>();
string text = "**" + Path.DirectorySeparatorChar;
int num = matchPattern.IndexOf(text, 0, StringComparison.OrdinalIgnoreCase);
if (num >= 0)
{
List<string> matchingDirectories = GetMatchingDirectories(#"Z:", matchPattern.Substring(0, num), 0);
string searchPattern = matchPattern.Substring(num + text.Length);
using (List<string>.Enumerator enumerator = matchingDirectories.GetEnumerator())
{
while (enumerator.MoveNext())
{
string current = enumerator.Current;
list.AddRange(Directory.GetFiles(current, searchPattern, SearchOption.AllDirectories));
}
return list;
}
}
int num2 = matchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (num2 >= 0)
{
List<string> matchingDirectories2 = GetMatchingDirectories(string.Empty, matchPattern.Substring(0, num2 + 1), 0);
string searchPattern2 = matchPattern.Substring(num2 + 1);
using (List<string>.Enumerator enumerator2 = matchingDirectories2.GetEnumerator())
{
while (enumerator2.MoveNext())
{
string current2 = enumerator2.Current;
try
{
list.AddRange(Directory.GetFiles(current2, searchPattern2, SearchOption.TopDirectoryOnly));
}
catch
{
}
}
return list;
}
}
try
{
list.AddRange(Directory.GetFiles(Directory.GetCurrentDirectory(), matchPattern, SearchOption.TopDirectoryOnly));
}
catch
{
}
return list;
}
private static List<string> GetMatchingDirectories(string rootDir, string pattern, int level)
{
if (level > 129)
{
return new List<string>();
}
List<string> list = new List<string>();
int num = pattern.IndexOf('*');
if (num >= 0)
{
int num2 = pattern.Substring(0, num).LastIndexOf(Path.DirectorySeparatorChar);
string text = (num2 >= 0) ? Path.Combine(rootDir, pattern.Substring(0, num2 + 1)) : rootDir;
if (text.Equals(string.Empty))
{
text = Directory.GetCurrentDirectory();
}
int num3 = pattern.IndexOf(Path.DirectorySeparatorChar, num);
if (num3 < 0)
{
num3 = pattern.Length;
}
string searchPattern = pattern.Substring(num2 + 1, num3 - num2 - 1);
try
{
string[] directories = Directory.GetDirectories(text, searchPattern, SearchOption.TopDirectoryOnly);
if (num3 < pattern.Length - 1)
{
string pattern2 = pattern.Substring(num3 + 1);
string[] array = directories;
for (int i = 0; i < array.Length; i++)
{
string rootDir2 = array[i];
list.AddRange(GetMatchingDirectories(rootDir2, pattern2, level + 1));
}
}
else
{
list.AddRange(directories);
}
return list;
}
catch
{
return list;
}
}
string text2 = Path.Combine(rootDir, pattern);
if (text2.Equals(string.Empty))
{
list.Add(Directory.GetCurrentDirectory());
}
else
{
if (Directory.Exists(text2))
{
list.Add(Path.GetFullPath(text2));
}
}
return list;
}
}
}

Resources