I need to count how many times a binary input needs to rotate to get its original form again for example if i enter 10101 it needs for rotation to 4 cyclic shifts to become 10101 again if i enter 010101 it needs for rotation to 2 cyclic shifts to become 010101 again or if i enter 111111 or 000000 it needs 1 cyclic shifts to become 111111 or 000000 again
my code
using System;
class Solution
{
public static void Main(string[] args)
{
var binarayInput = Console.ReadLine();
var a = binarayInput;
var b = binarayInput[^1] binarayInput[..^1];
Console.WriteLine(b);
var count = 0;
while(a !=b){
b = binarayInput[^1] binarayInput[..^1];
count ;
}
Console.WriteLine(count);
}
}
CodePudding user response:
Try this:
string originalInput = Console.ReadLine() string.Empty;
Console.WriteLine($"Input: {originalInput}");
string current = string.Join(string.Empty, originalInput.Select(c => c));
for(var i=0; i<originalInput.Length; i =1) {
var temp = CyclicShift(current);
Console.WriteLine($"Shift {i 1}: {temp}");
if(originalInput.Equals(temp)) {
Console.WriteLine($"Become original after {i 1} shifts.");
break;
}
current = temp;
}
string CyclicShift(string input) {
if(input.Length == 0) return string.Empty;
if(input.Length == 1) return input;
var newStr = input[^1] input[..^1];
return newStr;
}
Test:
Input: 10101
Shift 1: 11010
Shift 2: 01101
Shift 3: 10110
Shift 4: 01011
Shift 5: 10101
Become original after 5 shifts.
Input: 010101
Shift 1: 101010
Shift 2: 010101
Become original after 2 shifts.
Input: 111111
Shift 1: 111111
Become original after 1 shifts.
CodePudding user response:
If you are using .Net 6, you could take the advantage of .TakeLast()
and .SkipLast()
from System.Linq
when temporarily "building" your rotated string.
using System;
using System.Linq;
class Solution
{
public static void Main(string[] args)
{
var binaryInput = Console.ReadLine();
var shifts = 1;
while (binaryInput != string.Join("", binaryInput.TakeLast(shifts).Concat(binaryInput.SkipLast(shifts))))
{
shifts ;
}
Console.WriteLine(shifts);
}
}
When e.g. shifts == 3
, binaryInput.TakeLast(shifts)
will take the 3 last chars of binaryInput
(converted to an IEnumerable<char>
, because that is the return value of .TakeLast()
when it is called on a string
), and binaryInput.SkipLast(shifts)
will take all the chars of binaryInput
but the three last (also converted to an IEnumerable<char>
).
To stitch the two IEnumerable<char>
s back together to a string again, I am using .Concat()
to merge them into one IEnumerable<char>
, and then string.Join()
to convert it to a string that can be compared with binaryInput
.
Fiddle to try it out here.