Blockland Forums > Modification Help
Way to simplify SwapChar
(1/2) > >>
Ipquarx:
I've made a function that swaps the positions of two characters in a string.
It works fine, but I want to know if there's any way to simplify it.

Here's the code:
--- Code: ---function swapChar(%input, %p1, %p2)
{
%pt1 = %p1; %pt2 = %p2;
%p1 = Min(%pt1, %pt2);
%p2 = Max(%pt1, %pt2);

%c1 = getSubStr(%input, %p1, 1);
%c2 = getSubStr(%input, %p2, 1);

%b1 = %p1 > 0 ? getSubStr(%input, 0, %p1) : "";
%b2 = %p1+1 != %p2 ? getSubStr(%input, %p1+1, %p2-1) : "";
%f = %p2 < strLen(%input)-1 ? getSubStr(%input, %p2+1, strLen(%input)) : "";
return %b1 @ %c2 @ %b2 @ %c1 @ %f;
}
--- End code ---
Nexus:
assuming %p1 and %p2 are integers that represent the position of the character

function swapchar(%str, %a, %b)
{
   if(%a > %b)
   {
      %b = %temp;
      %b = %a;
      %a = %temp;
   }
   return getsubstr(%str, 0, %a-1) @ getsubstr(%str, %b, 1) @ getsubstr(%str, %a+1, %b-%a-1) @ getsubstr(%str, %a, 1) @ getsubstr(%str, %b+1, strlen(%str));
}

although of course this is reliant on good integer input.  I probably wouldn't even put in the check to make sure %b is larger than %a except it looks like you did that in yours and I imagine you would call me out on it.
Daenth:

--- Quote from: Nexus on May 06, 2012, 07:13:01 PM ---assuming %p1 and %p2 are integers that represent the position of the character

function swapchar(%str, %a, %b)
{
   if(%a > %b)
   {
      %b = %temp;
      %b = %a;
      %a = %temp;
   }
   return getsubstr(%str, 0, %a-1) @ getsubstr(%str, %b, 1) @ getsubstr(%str, %a+1, %b-%a-1) @ getsubstr(%str, %a, 1) @ getsubstr(%str, %b+1, strlen(%str));
}

although of course this is reliant on good integer input.  I probably wouldn't even put in the check to make sure %b is larger than %a except it looks like you did that in yours and I imagine you would call me out on it.

--- End quote ---
Shouldn't %b = %temp; be %temp = %b;?
Treynolds416:
Yes
Ipquarx:

--- Quote from: Nexus on May 06, 2012, 07:13:01 PM ---assuming %p1 and %p2 are integers that represent the position of the character

function swapchar(%str, %a, %b)
{
   if(%a > %b)
   {
      %b = %temp;
      %b = %a;
      %a = %temp;
   }
   return getsubstr(%str, 0, %a-1) @ getsubstr(%str, %b, 1) @ getsubstr(%str, %a+1, %b-%a-1) @ getsubstr(%str, %a, 1) @ getsubstr(%str, %b+1, strlen(%str));
}

although of course this is reliant on good integer input.  I probably wouldn't even put in the check to make sure %b is larger than %a except it looks like you did that in yours and I imagine you would call me out on it.

--- End quote ---
What if %a or %b is 0, and what if they are the same? %b-%a-1 will be -1, and if %a or %b is 0 (meaning the first charachter), it will also try to getsubstr with -1!
Navigation
Message Index
Next page

Go to full version