Reputation: 5552
I am ruby developer and for certain case I need to swap digits at odd places in 2 numbers in C#
.
I have coded in ruby in basic way like below,
a = 35321
b = 123456
a1, b1 = a.to_s.chars, b.to_s.chars # ['3', '5', '3'. '2', '1'], ['1', '2', '3', '4', '5', '6']
n = [a1.length, b1.length].min - 1 # => 4
swapped in below manner,
n.times do |i|
if i.odd?
temp = a1[i]
a1[i] = b1[i]
b1[i] = a1[i]
end
end
Or optimised code is below using step
method in ruby,
1.step(n,2) { |i| a1[i], b1[i] = b1[i], a1[i] }
And at the end I get numbers as per expectation as,
> a = a1.join.to_i
# => 32341
> b = b1.join.to_i
# => 153256
My problem is I could not figure out how can I do same in C#
Appreciated if anyone provide either suggestion.
Upvotes: 4
Views: 233
Reputation: 9771
There are plenty of ways in c#
to get your desired output but I give you a solution that you can understand easily,
First of all we declare your integer array in c#
like
int input1 = 35321;
int input2 = 123456;
int[] a = input1.ToString().Select(t => int.Parse(t.ToString())).ToArray();
int[] b = input2.ToString().Select(t => int.Parse(t.ToString())).ToArray();
Then we use traditional for loop to swap number between two array with odd index
for (int i = 0; i < a.Length; i++) //<= Loop through on first array
{
if (i % 2 != 0) //<= Check for odd index
{
int q = a[i]; //<= Take element from first array with current index
a[i] = b[i]; //<= Swap element from second array to first array on current index
b[i] = q; //<= Swap element from first array to second array on current index
}
}
Then we simply print your desired output by,
int number1 = Convert.ToInt32(string.Join("", a));
int number2 = Convert.ToInt32(string.Join("", b));
Console.WriteLine("Output for first array: \t" + number1);
Console.WriteLine("Output for second array: \t" + number2);
Output:
Upvotes: 1
Reputation: 58
Considering the inputs a and b will be strings. The below code should get you the desired result.
var result = string.Join("", b.ToString().Select((x, i) => (i % 2) == 0 || a.ToString().Length <= i ? x.ToString() : a.ToString().Substring(i, 1)));
this code will take into consideration the difference in length.
Edit:You can also implement using LINQ avoiding loops and considering a and b as numbers as shown below.
int[] ai = a.ToString().Select(x => int.Parse(x.ToString())).ToArray();
int[] bi = b.ToString().Select(x => int.Parse(x.ToString())).ToArray();
var number1 = string.Join("", bi.Select((x, i) => (i % 2) == 0 || ai.Count() <= i ? x.ToString() : ai[i].ToString()));
var number2 = string.Join("", ai.Select((x, i) => (i % 2) == 0 || bi.Count() <= i ? x.ToString() : bi[i].ToString()));
Console.WriteLine("Array 1:" + Convert.ToInt32(number1));
Console.WriteLine("Array 2:" + Convert.ToInt32(number2));
Upvotes: 1