shifting string to left - c#

We have a string: 0000029653. How to shift numbers by some value.
For example, shift by 4 then result must be :0296530000
There is operator or function for this?
Thanks

You could convert it to an number then do this:
Result = yournumber * Math.Pow(10, shiftleftby);
then convert it back to string and pad left with 0s

If you don't want to use substring and indexes, you can also play with Linq :
string inString = "0000029653";
var result = String.Concat(inString.Skip(4).Concat(inString.Take(4)));

public string Shift(string numberStr, int shiftVal)
{
string result = string.Empty;
int i = numberStr.Length;
char[] ch = numberStr.ToCharArray();
for (int j = shiftVal; result.Length < i; j++)
result += ch[j % i];
return result;
}

You could cast your numbers as ints to strings and back.
String number = "0000029653";
String shiftedNumber = number.Substring(4);

Below methods take the number n which tells how many times you want to shift/rotate the string. I have taken the MOD by length of string if the number is greater than the length of string.
public static void Rotate(ref string str, int n)
{
if (n < 1)
throw new Exception("Negative number for rotation"); ;
if (str.Length < 1) throw new Exception("0 length string");
if (n > str.Length) // If number is greater than the length of the string then take MOD of the number
{
n = n % str.Length;
}
StringBuilder s1=new StringBuilder(str.Substring(n,(str.Length - n)));
s1.Append(str.Substring(0,n));
str=s1.ToString();
}
///You can make a use of Skip and Take functions of the String operations
public static void Rotate1(ref string str, int n)
{
if (n < 1)
throw new Exception("Negative number for rotation"); ;
if (str.Length < 1) throw new Exception("0 length string");
if (n > str.Length)
{
n = n % str.Length;
}
str = String.Concat(str.Skip(n).Concat(str.Take(n)));
}

Related

Getting number of possible anagrams from a generic string, need a fast solution

I am currently working on an assignment where I need to write a small program that will take a generic string and should output how many possible anagrams that could be generated from the string.
The string that is the input can be up to 100 chars long and could include both lowercase and uppercase, in this case both lowercase and uppercase are considered distinct. The output should only be how many possible combinations, so I don't need to output the actual anagrams.The maximum timelimit is 1 second per string.
I have tried a number of diffrent ways of doing this, but one conclusion is that this should be solvable using some type of mathemathical algorithm.
The latest code I have tried with is this:
static void Main(string[] args)
{
string line;
while ((line = Console.ReadLine()) != null)
{
var uniqueStringArr = removeDuplicates(line);
Console.WriteLine(countDistinctPermutations(new string(uniqueStringArr)));
}
}
private static char[] removeDuplicates(string line)
{
var list = line.ToList();
return list.Distinct().ToArray();
}
static int MAX_CHAR = 100;
// Utility function to find factorial of n.
static int factorial(int n)
{
int fact = 1;
for (int i = 2; i <= n; i++)
fact = fact * i;
return fact;
}
// Returns count of distinct permutations
// of str.
static int countDistinctPermutations(String str)
{
int length = str.Length;
int[] freq = new int[MAX_CHAR];
// finding frequency of all the lower case
// alphabet and storing them in array of
// integer
for (int i = 0; i < length; i++)
if (str[i] >= 'a')
freq[str[i] - 'a']++;
// finding factorial of number of appearances
// and multiplying them since they are
// repeating alphabets
int fact = 1;
for (int i = 0; i < MAX_CHAR; i++)
fact = fact * factorial(freq[i]);
// finding factorial of size of string and
// dividing it by factorial found after
// multiplying
return factorial(length) / fact;
}
The thing is that this code does not give the correct answer for all my testcases.
The following sample data was provided for me :
Input string | Number of possible anagrams
at | 2
ordeals | 5040
abcdefghijklmnopqrstuvwxyz | 403291461126605635584000000
abcdefghijklmabcdefghijklm | 49229914688306352000000
abcdABCDabcd | 29937600
My code fixes the first two examples, but I get completly diffrent numbers for the other 3.
Is there anyone who can help me with this problem because I am running out of ideas ?
/Andreas
static BigInteger Factorial(long x)
{
return x <= 1 ? 1 : x * Factorial(x-1);
}
private static BigInteger NumberOfDistinctPermutationOf(string str)
{
BigInteger dividend = Factorial(str.Length);
foreach (char chr in str)
{
dividend /= Factorial(str.Count(c => c == chr));
str = str.Replace(chr.ToString(), string.Empty);
}
return dividend;
}
Description:
BigInteger Struct: Represents an arbitrarily large signed integer.
Enumerable.Count Method: Returns a number that represents how many elements in the specified sequence satisfy a condition.
String.Replace(String, String) Method: Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
GetNumberOfDistinctPermutation Method: Divides factorial of the length of the string by factorial of the number of occurrences of the char and then removes all occurrences of the char, for each char in the string.
static void Main(string[] args)
{
string line;
while ((line = Console.ReadLine()) != null)
{
Console.WriteLine($"{line} -> {countDistinctPermutations(line)}");
}
}
static BigInteger factorial(int n)
{
double fact = 1;
for (int i = 2; i <= n; i++)
fact = fact * i;
return fact;
}
static BigInteger countDistinctPermutations(String str)
{
// get a collection of {letter,occurences}
var duplicates = Array.GroupBy(p => p).Select(x => new { x.Key, count = x.Count() }).Where(x => x.count > 1);
BigInteger result = factorial(str.Length);
// foreach letter where occurence > 1 divide total permutations by the permutations for the occurence value (occurrence!)
foreach (var d in duplicates)
{
result /= factorial(d.count);
}
return result;
}
I only write code for a week so it's not that pretty but it works 100%.
static void Main(string[] args)
{
string inputData = Console.ReadLine();
Console.WriteLine(Solution(inputData));
}
static char[] convert(string text) // converting string to char[]
{
char[] newString = new char[text.Length];
for (int i = 0; i < text.Length; i++)
{
newString[i] = text[i];
}
return newString;
}
static double CalculateFctorial(double number) // calc. factorial
{
double factorial = 1;
for (int i = 1; i <= number; i++)
factorial *= i;
return factorial;
}
static int CountOcc(string text, char zet) // counting occurrences
{
int count = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == zet)
{
count++;
}
}
return count;
}
static double Solution(string text) // the soluton, counting occurences of
// each char in string and each factorial
{
double net = 0;
double sol = 1;
char[] newText = convert(text);
for (int i = 0; i <= newText.Length; i++)
{
if (text.Length > 0)
{
net = CountOcc(text, newText[i]);
sol = sol * CalculateFctorial(net);
if (newText[i] == text[0])
{ text = text.Trim(text[0]); }
}
}
double solution = CalculateFctorial(newText.Length) / sol;
return solution;
}

Divide the elements of a given string

I should divide the elements into several small substrings with equal length. The count of the substrings should be equal to the given partitions. If the string cannot be exactly divided into the given partitions, I must make all partitions except the last with equal lengths, and make the last one – the longest.
I've tried to make the first part, but it's not working in all cases. Can you show me a way but if it's possible with for-loops, etc.?
For example:
{abcd}, 3 partitions -> {a, b, cd}; {qrstuvwxyz}, 5 partitions -> {qr st uv wx yz}
private static List<string> Divide(List<string> input, int index, int partitions)
{
string stringToDivide = input[index];
input.RemoveAt(index);
string add = "";
if (stringToDivide.Length % partitions == 0)
{
for (int i = 0; i < stringToDivide.Length; i++)
{
add += stringToDivide[i] + " ";
}
input.Insert(index, add.Trim());
}
else
{
}
return input;
Console.WriteLine(string.Join(' ', input));
}
You can do something like this:
private static List<string> Divide(List<string> input, int index, int partitions)
{
var stringToDivide = input[index];
input.RemoveAt(index);
var stringToAdd = "";
var partitionLength = stringToDivide.Length / partitions;
for (int i = 0, partitionNum = 0; i < stringToDivide.Length; i++)
{
if (i % partitionLength == 0 && partitionNum != partitions) // skip space in last part
{
if (i > 0) // do not add leading space
{
stringToAdd += " ";
}
partitionNum++;
}
stringToAdd += stringToDivide[i];
}
input.Insert(index, stringToAdd);
return input;
}
This code adds spaces each partitionLength, but skips space for last string. Note that for long strings it's better to use StringBuilder.
stringToDivide.Length % partitions is the number of characters left over after dividing into partitions number of partitions.
stringToDivide.Length / partitions is the number of characters that should be in each partition except the last, which should have the left-over characters appended to it.
So just take the first partitions number of stringToDivide.Length / partitions length chunks, and append what's left over to the last chunk.
When the string is evenly divisible, stringToDivide.Length % partitions is zero, so it's not a special case.
public static List<string> DivideIntoPartitions(string stringToDivide, int partitions)
{
var parts = new List<string>(partitions);
var len = stringToDivide.Length;
if (len < partitions)
{
throw new ArgumentException("partitions should be less than length");
}
if (len % partitions == 0)
{
var eachSubstrLength = len / partitions;
for (int i = 0; i < stringToDivide.Length; i += eachSubstrLength)
{
parts.Add(stringToDivide.Substring(i, eachSubstrLength));
}
}
else
{
var nextDivisibleNumber = len + (partitions - (len % partitions));
var lengthOfLastSubstr = nextDivisibleNumber / partitions;
var lastItem = stringToDivide.Substring((len - lengthOfLastSubstr));
stringToDivide = stringToDivide.Remove((len - lengthOfLastSubstr));
var chunksize = stringToDivide.Length / (partitions - 1);
for (int i = 0; i < stringToDivide.Length; i += chunksize)
{
parts.Add(stringToDivide.Substring(i, chunksize));
}
parts.Add(lastItem);
}
return parts;
}
var result = DivideIntoPartitions("qrstuvwxyz", 3);

Reverse binary representation of int (only significant bits)

I'm trying to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11 right?
Here's my code:
static void Main(string[] args)
{
Console.WriteLine("Enter a Number");
int numb = int.Parse(Console.ReadLine());
int reverse = 0;
while (numb > 0)
{
int rem = numb % 10;
reverse = (reverse * 10) + rem;
numb = numb / 10;
}
Console.WriteLine("Reverse number={0}", reverse);
Console.ReadLine();
}
By this code I only get the numbers to reverse (13 -> 31)...
The input should contain a single line with an integer N, 1≤N≤1000000000 and I want my output in one line with one integer, the number I want to get by reversing the binary representation of N.
Something like that
// 13 = 1101b
int value = 13;
// 11 = 1011b
int result = Convert.ToInt32(new String(
Convert.ToString(value, 2)
.Reverse()
.ToArray()), 2);
Explanation:
Convert.ToString(value, 2) returns value in binary representation ("1101")
Reverse().ToArray() - reverse the string ('1','0','1','1') as sequence of characters and converts to array char[].
new String(...) constructs string "1011" from array of char
finally, Convert.ToInt32(..., 2) convert binary representation back to int
You can use Convert.ToString and Convert.ToInt32 methods, where 2 means binary:
int numb = int.Parse(Console.ReadLine());
var reversedString = Convert.ToString(numb, 2).ReverseString();
var result = Convert.ToInt32(reversedString, 2);
...
public static string ReverseString(this string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
A fun excercise would be doing this without using the string conversion.
I have very little experience with bit twiddling so there is probably a faster and better way of doing this, but this seems to work:
public static IEnumerable<bool> ToBinary(this int n)
{
for (int i = 0; i < 32; i++)
{
yield return (n & (1 << i)) != 0;
}
}
public static int ToInt(this IEnumerable<bool> b)
{
var n = 0;
var counter = 0;
foreach (var i in b.Trim().Take(32))
{
n = n | (i ? 1 : 0) << counter;
counter++
}
return n;
}
private static IEnumerable<bool> Trim(this IEnumerable<bool> list)
{
bool trim = true;
foreach (var i in list)
{
if (i)
{
trim = false;
}
if (!trim)
{
yield return i;
}
}
}
And now you'd call it like this:
var reversed = n.ToBinary().Reverse().ToInt();

Mask out part first 12 characters of string with *?

How can I take the value 123456789012345 or 1234567890123456 and turn it into:
************2345 and ************3456
The difference between the strings above is that one contains 15 digits and the other contains 16.
I have tried the following, but it does not keep the last 4 digits of the 15 digit number and now matter what the length of the string, be it 13, 14, 15, or 16, I want to mask all beginning digits with a *, but keep the last 4. Here is what I have tried:
String.Format("{0}{1}", "************", str.Substring(11, str.Length - 12))
Something like this:
string s = "1234567890123"; // example
string result = s.Substring(s.Length - 4).PadLeft(s.Length, '*');
This will mask all but the last four characters of the string. It assumes that the source string is at least 4 characters long.
using System;
class Program
{
static void Main()
{
var str = "1234567890123456";
if (str.Length > 4)
{
Console.WriteLine(
string.Concat(
"".PadLeft(12, '*'),
str.Substring(str.Length - 4)
)
);
}
else
{
Console.WriteLine(str);
}
}
}
Easiest way: Create an extension method to extract the last four digits. Use that in your String.Format call.
For example:
public static string LastFour(this string value)
{
if (string.IsNullOrEmpty(value) || value.length < 4)
{
return "0000";
}
return value.Substring(value.Length - 4, 4)
}
In your code:
String.Format("{0}{1}", "************", str.LastFour());
In my opinion, this leads to more readable code, and it's reusable.
EDIT: Perhaps not the easiest way, but an alternative way that may produce more maintainable results. <shrug/>
Try this:
var maskSize = ccDigits.Length - 4;
var mask = new string('*', maskSize) + ccDigits.Substring(maskSize);
LINQ:
char maskBy = '*';
string input = "123456789012345";
int count = input.Length <= 4 ? 0 : input.Length - 4;
string output = new string(input.Select((c, i) => i < count ? maskBy : c).ToArray());
static private String MaskInput(String input, int charactersToShowAtEnd)
{
if (input.Length < charactersToShowAtEnd)
{
charactersToShowAtEnd = input.Length;
}
String endCharacters = input.Substring(input.Length - charactersToShowAtEnd);
return String.Format(
"{0}{1}",
"".PadLeft(input.Length - charactersToShowAtEnd, '*'),
endCharacters
);
}
Adjust the function header as required, call with:
MaskInput("yourInputHere", 4);
private string MaskDigits(string input)
{
//take first 6 characters
string firstPart = input.Substring(0, 6);
//take last 4 characters
int len = input.Length;
string lastPart = input.Substring(len - 4, 4);
//take the middle part (****)
int middlePartLenght = len - (firstPart.Length + lastPart.Length);
string middlePart = new String('*', middlePartLenght);
return firstPart + middlePart + lastPart;
}
MaskDigits("1234567890123456");
// output : "123456******3456"
Try the following:
private string MaskString(string s)
{
int NUM_ASTERISKS = 4;
if (s.Length < NUM_ASTERISKS) return s;
int asterisks = s.Length - NUM_ASTERISKS;
string result = new string('*', asterisks);
result += s.Substring(s.Length - NUM_ASTERISKS);
return result;
}
Regex with a match evaluator will do the job
string filterCC(string source) {
var x=new Regex(#"^\d+(?=\d{4}$)");
return x.Replace(source,match => new String('*',match.Value.Length));
}
This will match any number of digits followed by 4 digits and the end (it won't include the 4 digits in the replace). The replace function will replace the match with a string of * of equal length.
This has the additional benefit that you could use it as a validation algorthim too. Change the first + to {11,12} to make it match a total of 15 or 16 chars and then you can use x.IsMatch to determine validity.
EDIT
Alternatively if you always want a 16 char result just use
return x.Replace(source,new String('*',12));
// "123456789".MaskFront results in "****56789"
public static string MaskFront(this string str, int len, char c)
{
var strArray = str.ToCharArray();
for (var i = 0; i < len; i++)
{
if(i < strArray.Length)
{
strArray[i] = c;
}
else
{
break;
}
}
return string.Join("", strArray);
}
// "123456789".MaskBack results in "12345****"
public static string MaskBack(this string str, int len, char c)
{
var strArray = str.ToCharArray();
var tracker = strArray.Length - 1;
for (var i = 0; i < len; i++)
{
if (tracker > -1)
{
strArray[tracker] = c;
tracker--;
}
else
{
break;
}
}
return string.Join("", strArray);
}
Try this out:
static string Mask(string str)
{
if (str.Length <= 4) return str;
Regex rgx = new Regex(#"(.*?)(\d{4})$");
string result = String.Empty;
if (rgx.IsMatch(str))
{
for (int i = 0; i < rgx.Matches(str)[0].Groups[1].Length; i++)
result += "*";
result += rgx.Matches(str)[0].Groups[2];
return result;
}
return str;
}
Mask from start and from end with sending char
public static string Maskwith(this string value, int fromStart, int fromEnd, char ch)
{
return (value?.Length >= fromStart + fromEnd) ?
string.Concat(Enumerable.Repeat(ch, fromStart)) + value.Substring(fromStart, value.Length - (fromStart + fromEnd)) + string.Concat(Enumerable.Repeat(ch, fromEnd))
: "";
} //Console.WriteLine("mytestmask".Maskwith(2,3,'*')); **testm***
show chars from start and from end by passing value and mask the middle
public static string MasktheMiddle(this string value, int visibleCharLength, char ch)
{
if (value?.Length <= (visibleCharLength * 2))
return string.Concat(Enumerable.Repeat(ch,value.Length));
else
return value.Substring(0, visibleCharLength) + string.Concat(Enumerable.Repeat(ch, value.Length - (visibleCharLength * 2))) + value.Substring(value.Length - visibleCharLength);
} //Console.WriteLine("mytestmask".MasktheMiddle(2,'*')); Result: my******sk
How can I take the value 123456789012345 or 1234567890123456 and turn it into:
************2345 and ************3456
one more way to do this:
var result = new string('*',0,value.Length - 4) + new string(value.Skip(value.Length - 4).ToArray())
// or using string.Join
An extension method using C# 8's index and range:
public static string MaskStart(this string input, int showNumChars, char maskChar = '*') =>
input[^Math.Min(input.Length, showNumChars)..]
.PadLeft(input.Length, maskChar);
A simple way
string s = "1234567890123"; // example
int l = s.Length;
s = s.Substring(l - 4);
string r = new string('*', l);
r = r + s;

Function to generate alpha numeric sequence number based on input number

I am trying to develope a routine in C# that will take a given input integer and return a 6 character alpha numeric string based on a predefined possible set of characters.
The possible characters to use are:
"0123456789ABCDEFGHJKLMNPQRSTUVWXYZ" (note that the letter "I" and "O" are not in the set.)
Therefore given the input of 1, the output should be "000001", input of 9 would output "000009", input of 10 would output "00000A", input of 12345 would output "000AP3", and so on.
I am having a hard time coming up with an elegant solution to this problem. I know I must be approaching this the hard way so I'm looking for some help.
Thanks!
int value = 12345;
string alphabet = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var stack = new Stack<char>();
while (value > 0)
{
stack.Push(alphabet[value % alphabet.Length]);
value /= alphabet.Length;
}
string output = new string(stack.ToArray()).PadLeft(6, '0');
The direct solution would simply be to iteratively divide your input value by N (the size of the character set), and take the remainder each time to index into the character set, and build up the output string character-by-character.
internal class Program {
private static void Main(string[] args) {
int value = 38;
const string alphabet = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
string result = ToBase(value, alphabet);
Console.WriteLine(result);
}
private static string ToBase(int value, string alphabet) {
if (value == 0) return alphabet[0].ToString();
var result = new StringBuilder();
while (value > 0) {
int digit = value % alphabet.Length;
value = (value - digit) / alphabet.Length;
result.Insert(0, alphabet[digit]);
}
return result.ToString();
}
}
you do zero-padding
LukeH answer modified for Generating Alphanemuric to numeric and vice versa
int value = 12345;
string alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var stack = new Stack<char>();
while (value > 0)
{
int index = value % alphabet.Length;
stack.Push(alphabet[index]);
value /= alphabet.Length;
}
string output = new string(stack.ToArray()).PadLeft(6, '0');
double intNumber = 0;
int charPos = 0;
for (var i = output.Length-1; i >=0;i--)
{
int val = output[i];
if (val >= 48 && val <= 57)
intNumber += (val - 48) * (Math.Pow(36, charPos++));
else if (val >= 65 && val <= 90)
intNumber += (val - 55) * (Math.Pow(36, charPos++));
}

Categories

Resources