Background
I am currently in an AP Comp Sci A: Java class, and I want to start some of my friends on code golfing. I have a challenge from the course, and I would like to see how many bytes the community can do this challenge in.
Challenge details:
Given two input strings, the main string and the pivot string, do the following:
If the pivot string is exactly once as a substring of the main string, the part of the main string that comes before the pivot string shall be swapped with the part that comes after, while preserving the order within said subtrings being swapped.
For example:
If the pivot string is empty or the pivot string is not found within the main string, the program does not have to have defined behavior.
If there is more than one instance of the pivot string, the split should occur at the first and only the first instance of the pivot.
Examples:
Given the main string OneTwoThreeTwoOne
and the pivot string Two
, the output should be ThreeTwoOneTwoOne
.
Given the main string 1Two2Two3Two4
and pivot Two
, the output should be 2Two3Two4Two1
.
Given the main string OneTwoThree
and the pivot string "Two", the output should be ThreeTwoOne
.
Given the main string the rabbit is faster than the turtle
and the pivot string
is faster than
(note the single space trailing and preceding), the output should be the turtle is faster than the rabbit
.
Given the main string 1-2-3-4-5-6
and the pivot -
, the output should be 2-3-4-5-6-1
.
Afterword:
This is my first ever question on code golf, so if you have suggestions or constructive criticism, then feel free to say so.
Additionally, my code for this project (written in Java because the course focuses on that) can be found below. If you have any tips, I'd love to see them. Its currently 363 bytes, but I bet you guys can come up with much better and smaller solutions.
import java.util.Scanner;interface Main{static<T>void D(T f){System.out.println(f);}static void main(String[]A){Scanner s=new Scanner(System.in);D("Enter the first String:");String a=s.nextLine();D("Enter the pivot String:");String p=s.nextLine();if(p.isEmpty()|!a.contains(p)){D("Error: Pivot String not found.");return;}String w[]=a.split(p,2);D(w[1]+p+w[0]);}}
Note: The text for the inputs and for the case that the pivot string is not found is mandatory for the original assignment, but not for this challenge.
pivot='-'
andmain='1-2-3-4-5-6'
? Most submissions output2-3-4-5-6-1
for this, but as I understand the challenge it should be2-1-3-4-5-6
. \$\endgroup\$2-3-4-5-6-1
. \$\endgroup\$