I have a sample code like this:
CString A = _T("abc");
CString B = _T("xyz");
CString res;
now to concat these two above strings, which one should I prefer:
res = A + _T(" ") + B;
or
res.Format(_T("%s %s"), A, B);
Made a sample function and ran the the bellow code
CString str1 = _T("abc");
CString str2 = _T("xyz");
CString strRes;
DWORD dwTickCount = GetTickCount();
const int LoopCount = 1000000;
for(int nIdx = 0; nIdx < LoopCount; nIdx++)
{
strRes = str1 + _T(" ") + str2;
}
dwTickCount = GetTickCount() - dwTickCount;
The value of dwTickCount was 2656. But while checking the second case,
CString str1 = _T("abc");
CString str2 = _T("xyz");
CString strRes;
DWORD dwTickCount = GetTickCount();
const int LoopCount = 1000000;
for(int nIdx = 0; nIdx < LoopCount; nIdx++)
{
strRes.Format(_T("%s %s"), str1, str2);
}
dwTickCount = GetTickCount() - dwTickCount;
The value of dwTickCount was 453 only.
Hence I can say, the Format approach is about 6 times faster.
Related
I need to multiply two values - weight and currency (Visual c++, mfc). E.g.:
a=11.121;
b=12.11;
c=a*b;
Next I have to round "с" to 2 digits after point (currency value, e.g. 134.68). What the best data types and rounding function for this variables? The rounding procedure must be mathematically correct.
P.S. The problem was solved by very ugly but working part of code:
CString GetPriceSum(CString weight,CString price)
{
price.Replace(".", "");
price = price + "0";
if (weight.Find(".") == -1) { weight = weight + ".000"; }
weight.Replace(".", "");
unsigned long long int iprice = atoi(price);
unsigned long long int iweight = atoi(weight);
unsigned long long int isum = iprice * iweight;
CString sum = ""; sum.Format("%llu", isum);
CString r1 = sum.Right(1);
if (atoi(r1) >= 5) { isum += 10; }
CString r2 = sum.Mid(sum.GetLength() - 2, 1);
if (atoi(r2) >= 5) { isum += 100; sum.Format("%llu", isum);}
r2 = sum.Mid(sum.GetLength() - 3, 1);
if (atoi(r2) >= 5) { isum += 1000; sum.Format("%llu", isum);}
r2 = sum.Mid(sum.GetLength() - 4, 1);
if (atoi(r2) >= 5) { isum += 10000; sum.Format("%llu", isum);}
CString finsum = ""; finsum.Format("%llu", isum);
finsum.Insert(finsum.GetLength() - 6, ".");
finsum.Delete(finsum.GetLength() - 4, 4);
if (finsum.Left(1) == ".") { finsum = "0" + finsum; }
return finsum;
}
How about this: let's start from
API I use, counts values using some other language. And they round they values mathematically correct.
In your other question, you got those value as strings. You can construct an integer from those digits (remove decimal point). Assuming that the product fits in a 64-bit int, you can multiply them exactly. Now you can manually round to a desired precision and drop unneeded digits.
Code example (you may want to add error checking):
#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <iostream>
#include <sstream>
int main()
{
std::string a = "40.50";
std::string b = "0.490";
long long l1, dec1, l2, dec2;
sscanf(a.data(), "%lld.%lld", &l1, &dec1);
l1 = l1 * 100 + dec1;
sscanf(b.data(), "%lld.%lld", &l2, &dec2);
l2 = l2 * 1000 + dec2;
long long r = l1 * l2;
r /= 100;
int rem = r % 10;
r /= 10;
if (rem >= 5)
r++;
std::stringstream ss;
ss << r / 100 << "." << std::setw(2) << std::setfill('0') << r % 100;
std::cout << ss.str();
}
You can also use stringstream instead of sscanf to parse the strings.
Here is the little part of my code, I'm trying to convert my string operants into integer when I need it with the atoi. And I am encountering an error "uninitialized local variable ". How could I fix this problem?
CDC * pDC = GetDC();
CSize cz;
input1.GetWindowTextW(operant1);
input2.GetWindowTextW(operant2);
combo.GetWindowTextW(advanced_text);
if(groupCheckRadio == 0){ //AND
const char* operant1;
const char* operant2;
int num1 = atoi(operant1);
int num2 = atoi(operant2);
result = (num1 & num2);
}
if(groupCheckRadio == 1){ //OR
const char* operant1;
const char* operant2;
int num1 = atoi(operant1);
int num2 = atoi(operant2);
result = (num1 | num2);
}
if(groupCheckRadio == 2){ //XOR
const char* operant1;
const char* operant2;
int num1 = atoi(operant1);
int num2 = atoi(operant2);
result = (num1 ^ num2);
}
//shifting bits
if(checkShift.GetCheck() == 1){
int selected_index = combo.GetCurSel();
combo.GetLBText(selected_index,advanced_text);
}
If anyone If anyone wants to convert Cstring to integer after that, they can solve it using _ttof
CString operant1,operant2,bit,advanced_text,result,num_bin;
double numd1,numd2,resultd,bind,numdbin;
input1.GetWindowTextW(operant1);
input2.GetWindowTextW(operant2);
combo.GetWindowTextW(advanced_text);
input_bit.GetWindowTextW(num_bin);
CDC * pDC = GetDC();
CSize cz;
cz = pDC->GetTextExtent(result);
resultd = _ttof(result);
numd1 = _ttof(operant1);
numd2 = _ttof(operant2);
unsigned int resulti = int (resultd);
unsigned int num1 = int (numd1);
unsigned int num2 = int (numd2);
''
I'm posting this although much has already been posted about this question. I didn't want to post as an answer since it's not working. The answer to this post (Finding the rank of the Given string in list of all possible permutations with Duplicates) did not work for me.
So I tried this (which is a compilation of code I've plagiarized and my attempt to deal with repetitions). The non-repeating cases work fine. BOOKKEEPER generates 83863, not the desired 10743.
(The factorial function and letter counter array 'repeats' are working correctly. I didn't post to save space.)
while (pointer != length)
{
if (sortedWordChars[pointer] != wordArray[pointer])
{
// Swap the current character with the one after that
char temp = sortedWordChars[pointer];
sortedWordChars[pointer] = sortedWordChars[next];
sortedWordChars[next] = temp;
next++;
//For each position check how many characters left have duplicates,
//and use the logic that if you need to permute n things and if 'a' things
//are similar the number of permutations is n!/a!
int ct = repeats[(sortedWordChars[pointer]-64)];
// Increment the rank
if (ct>1) { //repeats?
System.out.println("repeating " + (sortedWordChars[pointer]-64));
//In case of repetition of any character use: (n-1)!/(times)!
//e.g. if there is 1 character which is repeating twice,
//x* (n-1)!/2!
int dividend = getFactorialIter(length - pointer - 1);
int divisor = getFactorialIter(ct);
int quo = dividend/divisor;
rank += quo;
} else {
rank += getFactorialIter(length - pointer - 1);
}
} else
{
pointer++;
next = pointer + 1;
}
}
Note: this answer is for 1-based rankings, as specified implicitly by example. Here's some Python that works at least for the two examples provided. The key fact is that suffixperms * ctr[y] // ctr[x] is the number of permutations whose first letter is y of the length-(i + 1) suffix of perm.
from collections import Counter
def rankperm(perm):
rank = 1
suffixperms = 1
ctr = Counter()
for i in range(len(perm)):
x = perm[((len(perm) - 1) - i)]
ctr[x] += 1
for y in ctr:
if (y < x):
rank += ((suffixperms * ctr[y]) // ctr[x])
suffixperms = ((suffixperms * (i + 1)) // ctr[x])
return rank
print(rankperm('QUESTION'))
print(rankperm('BOOKKEEPER'))
Java version:
public static long rankPerm(String perm) {
long rank = 1;
long suffixPermCount = 1;
java.util.Map<Character, Integer> charCounts =
new java.util.HashMap<Character, Integer>();
for (int i = perm.length() - 1; i > -1; i--) {
char x = perm.charAt(i);
int xCount = charCounts.containsKey(x) ? charCounts.get(x) + 1 : 1;
charCounts.put(x, xCount);
for (java.util.Map.Entry<Character, Integer> e : charCounts.entrySet()) {
if (e.getKey() < x) {
rank += suffixPermCount * e.getValue() / xCount;
}
}
suffixPermCount *= perm.length() - i;
suffixPermCount /= xCount;
}
return rank;
}
Unranking permutations:
from collections import Counter
def unrankperm(letters, rank):
ctr = Counter()
permcount = 1
for i in range(len(letters)):
x = letters[i]
ctr[x] += 1
permcount = (permcount * (i + 1)) // ctr[x]
# ctr is the histogram of letters
# permcount is the number of distinct perms of letters
perm = []
for i in range(len(letters)):
for x in sorted(ctr.keys()):
# suffixcount is the number of distinct perms that begin with x
suffixcount = permcount * ctr[x] // (len(letters) - i)
if rank <= suffixcount:
perm.append(x)
permcount = suffixcount
ctr[x] -= 1
if ctr[x] == 0:
del ctr[x]
break
rank -= suffixcount
return ''.join(perm)
If we use mathematics, the complexity will come down and will be able to find rank quicker. This will be particularly helpful for large strings.
(more details can be found here)
Suggest to programmatically define the approach shown here (screenshot attached below) given below)
I would say David post (the accepted answer) is super cool. However, I would like to improve it further for speed. The inner loop is trying to find inverse order pairs, and for each such inverse order, it tries to contribute to the increment of rank. If we use an ordered map structure (binary search tree or BST) in that place, we can simply do an inorder traversal from the first node (left-bottom) until it reaches the current character in the BST, rather than traversal for the whole map(BST). In C++, std::map is a perfect one for BST implementation. The following code reduces the necessary iterations in loop and removes the if check.
long long rankofword(string s)
{
long long rank = 1;
long long suffixPermCount = 1;
map<char, int> m;
int size = s.size();
for (int i = size - 1; i > -1; i--)
{
char x = s[i];
m[x]++;
for (auto it = m.begin(); it != m.find(x); it++)
rank += suffixPermCount * it->second / m[x];
suffixPermCount *= (size - i);
suffixPermCount /= m[x];
}
return rank;
}
#Dvaid Einstat, this was really helpful. It took me a WHILE to figure out what you were doing as I am still learning my first language(C#). I translated it into C# and figured that I'd give that solution as well since this listing helped me so much!
Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace CsharpVersion
{
class Program
{
//Takes in the word and checks to make sure that the word
//is between 1 and 25 charaters inclusive and only
//letters are used
static string readWord(string prompt, int high)
{
Regex rgx = new Regex("^[a-zA-Z]+$");
string word;
string result;
do
{
Console.WriteLine(prompt);
word = Console.ReadLine();
} while (word == "" | word.Length > high | rgx.IsMatch(word) == false);
result = word.ToUpper();
return result;
}
//Creates a sorted dictionary containing distinct letters
//initialized with 0 frequency
static SortedDictionary<char,int> Counter(string word)
{
char[] wordArray = word.ToCharArray();
int len = word.Length;
SortedDictionary<char,int> count = new SortedDictionary<char,int>();
foreach(char c in word)
{
if(count.ContainsKey(c))
{
}
else
{
count.Add(c, 0);
}
}
return count;
}
//Creates a factorial function
static int Factorial(int n)
{
if (n <= 1)
{
return 1;
}
else
{
return n * Factorial(n - 1);
}
}
//Ranks the word input if there are no repeated charaters
//in the word
static Int64 rankWord(char[] wordArray)
{
int n = wordArray.Length;
Int64 rank = 1;
//loops through the array of letters
for (int i = 0; i < n-1; i++)
{
int x=0;
//loops all letters after i and compares them for factorial calculation
for (int j = i+1; j<n ; j++)
{
if (wordArray[i] > wordArray[j])
{
x++;
}
}
rank = rank + x * (Factorial(n - i - 1));
}
return rank;
}
//Ranks the word input if there are repeated charaters
//in the word
static Int64 rankPerm(String word)
{
Int64 rank = 1;
Int64 suffixPermCount = 1;
SortedDictionary<char, int> counter = Counter(word);
for (int i = word.Length - 1; i > -1; i--)
{
char x = Convert.ToChar(word.Substring(i,1));
int xCount;
if(counter[x] != 0)
{
xCount = counter[x] + 1;
}
else
{
xCount = 1;
}
counter[x] = xCount;
foreach (KeyValuePair<char,int> e in counter)
{
if (e.Key < x)
{
rank += suffixPermCount * e.Value / xCount;
}
}
suffixPermCount *= word.Length - i;
suffixPermCount /= xCount;
}
return rank;
}
static void Main(string[] args)
{
Console.WriteLine("Type Exit to end the program.");
string prompt = "Please enter a word using only letters:";
const int MAX_VALUE = 25;
Int64 rank = new Int64();
string theWord;
do
{
theWord = readWord(prompt, MAX_VALUE);
char[] wordLetters = theWord.ToCharArray();
Array.Sort(wordLetters);
bool duplicate = false;
for(int i = 0; i< theWord.Length - 1; i++)
{
if(wordLetters[i] < wordLetters[i+1])
{
duplicate = true;
}
}
if(duplicate)
{
SortedDictionary<char, int> counter = Counter(theWord);
rank = rankPerm(theWord);
Console.WriteLine("\n" + theWord + " = " + rank);
}
else
{
char[] letters = theWord.ToCharArray();
rank = rankWord(letters);
Console.WriteLine("\n" + theWord + " = " + rank);
}
} while (theWord != "EXIT");
Console.WriteLine("\nPress enter to escape..");
Console.Read();
}
}
}
If there are k distinct characters, the i^th character repeated n_i times, then the total number of permutations is given by
(n_1 + n_2 + ..+ n_k)!
------------------------------------------------
n_1! n_2! ... n_k!
which is the multinomial coefficient.
Now we can use this to compute the rank of a given permutation as follows:
Consider the first character(leftmost). say it was the r^th one in the sorted order of characters.
Now if you replace the first character by any of the 1,2,3,..,(r-1)^th character and consider all possible permutations, each of these permutations will precede the given permutation. The total number can be computed using the above formula.
Once you compute the number for the first character, fix the first character, and repeat the same with the second character and so on.
Here's the C++ implementation to your question
#include<iostream>
using namespace std;
int fact(int f) {
if (f == 0) return 1;
if (f <= 2) return f;
return (f * fact(f - 1));
}
int solve(string s,int n) {
int ans = 1;
int arr[26] = {0};
int len = n - 1;
for (int i = 0; i < n; i++) {
s[i] = toupper(s[i]);
arr[s[i] - 'A']++;
}
for(int i = 0; i < n; i++) {
int temp = 0;
int x = 1;
char c = s[i];
for(int j = 0; j < c - 'A'; j++) temp += arr[j];
for (int j = 0; j < 26; j++) x = (x * fact(arr[j]));
arr[c - 'A']--;
ans = ans + (temp * ((fact(len)) / x));
len--;
}
return ans;
}
int main() {
int i,n;
string s;
cin>>s;
n=s.size();
cout << solve(s,n);
return 0;
}
Java version of unrank for a String:
public static String unrankperm(String letters, int rank) {
Map<Character, Integer> charCounts = new java.util.HashMap<>();
int permcount = 1;
for(int i = 0; i < letters.length(); i++) {
char x = letters.charAt(i);
int xCount = charCounts.containsKey(x) ? charCounts.get(x) + 1 : 1;
charCounts.put(x, xCount);
permcount = (permcount * (i + 1)) / xCount;
}
// charCounts is the histogram of letters
// permcount is the number of distinct perms of letters
StringBuilder perm = new StringBuilder();
for(int i = 0; i < letters.length(); i++) {
List<Character> sorted = new ArrayList<>(charCounts.keySet());
Collections.sort(sorted);
for(Character x : sorted) {
// suffixcount is the number of distinct perms that begin with x
Integer frequency = charCounts.get(x);
int suffixcount = permcount * frequency / (letters.length() - i);
if (rank <= suffixcount) {
perm.append(x);
permcount = suffixcount;
if(frequency == 1) {
charCounts.remove(x);
} else {
charCounts.put(x, frequency - 1);
}
break;
}
rank -= suffixcount;
}
}
return perm.toString();
}
See also n-th-permutation-algorithm-for-use-in-brute-force-bin-packaging-parallelization.
I would like to know how to write code that performs a UTF-8 to Latin(ISO-8859-1) Conversion in C++.
The following website does the conversion required:
http://www.unicodetools.com/unicode/utf8-to-latin-converter.php
Inserting value: úsername
provides the result: úsername
I've got a piece of code that does a similar job from a previous post but doesn't seem to convert the string
int utf8_to_unicode(std::deque<int> &coded)
{
int charcode = 0;
int t = coded.front();
coded.pop_front();
if (t < 128)
{
return t;
}
int high_bit_mask = (1 << 6) -1;
int high_bit_shift = 0;
int total_bits = 0;
const int other_bits = 6;
while((t & 0xC0) == 0xC0)
{
t <<= 1;
t &= 0xff;
total_bits += 6;
high_bit_mask >>= 1;
high_bit_shift++;
charcode <<= other_bits;
charcode |= coded.front() & ((1 << other_bits)-1);
coded.pop_front();
}
charcode |= ((t >> high_bit_shift) & high_bit_mask) << total_bits;
return charcode;
}
Help please!
You need the iconv(3) function from libiconv. The first argument (some iconv_t) to the iconv conversion function should be obtained by iconv_open(3) at program initialization, probably with
ic = iconv_open("ISO-8859-1","UTF-8");
(where ic is some static or global iconv_t variable).
int DownloadFtpDirectory(TCHAR* DirPath) {
WIN32_FIND_DATA FileData;
UINT a;
TCHAR* APP_NAME = TEXT("ftpcli");
TCHAR* f;
int j = 5;
do {
j++;
f = _tcsninc(DirPath, j);
}while (_tcsncmp(f, TEXT("/"), 1));
TCHAR* PATH_FTP = wcsncpy(new TCHAR[j], DirPath, j);
After the last line gets a string in which there is no line ending character, how to fix this?
P.S. how to do so would be out of line "ftp://ftp.microsoft.com/bussys/", get a string ftp.microsoft.com if both strings are TCHAR ?
TCHAR* PATH_FTP = wcsncpy(new TCHAR[j+1], DirPath, j);
PATH_FTP[j] = TEXT('\0');