-2

I was asked this in a technical interview. I have no idea whatsoever please please help me.

it goes in infinite loop. I just cant find the correct logic. not once, but twice i came across this kind of a question, so please help

public static int numberOfCharsInString(String sentence) 
{

    int numberOfChars = 0,i=0;

    while (!sentence.equals("")) 
    {
        sentence = sentence.substring(1);
        ++numberOfChars;
    }
        return numberOfChars;
}
public static void reverseSequenceOfWords(String inp)
{
    int len=numberOfCharsInString(inp);
    char[] in=inp.toCharArray();
    int i=0;
    for(i=len-1;i>=0;i--)
    {
        if(in[i]==' ')
        {
            while(!in.equals("")||in.equals(" "))
            {
                System.out.print(in[i]+" ");
            }
        }
        else if(in[i]=='\0')
        {
            break;
        }

    }

}
public static void main(String[] args)
{   
    int length=0;
    String inpstring = "";
        InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader reader = new BufferedReader(input);
    try
    {
        System.out.print("Enter a string to reverse:");
        inpstring = reader.readLine();
        length=numberOfCharsInString(inpstring);
        System.out.println("Number of Characters: "+length);
        reverseSequenceOfWords(inpstring);
    }
    catch (Exception e)
            {
              e.printStackTrace();
        }       
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • Split the string into an array based on space delimiter and print the array in reverse – blank Mar 04 '14 at 08:58
  • 1
    @blank Not very helpful unless you explain how to do that *without* using `String.split` or any other "standard function". – Marko Topolnik Mar 04 '14 at 08:59
  • @MarkoTopolnik then the question becomes how to split a string without split – blank Mar 04 '14 at 09:01
  • @MarkoTopolnik But then again, everything you do with a `String` to reverse it will at some point use a "standard function" ;) – Mark Rotteveel Mar 04 '14 at 09:01
  • 1
    @MarkRotteveel Was just going to ask OP about that :) There must be a defined minimal set of allowed methods. But you can guess what those would be: `charAt` is one, `System.out.print` another. – Marko Topolnik Mar 04 '14 at 09:01

5 Answers5

0
String[] array = "Are you crazy".split(" ");
for (int i = array.length - 1; i >= 0; --i) {
   System.out.print(array[i] + " ");
}
lance-java
  • 25,497
  • 4
  • 59
  • 101
  • "without the use of any standard functions" – TheLostMind Mar 04 '14 at 08:59
  • if ( i > 0 ) { print " "; } then print the word. – Pakspul Mar 04 '14 at 08:59
  • 1
    @T.J.Crowder the .split() is the standard function here. – Solace Mar 04 '14 at 09:01
  • @Solace: Doh! Of course. – T.J. Crowder Mar 04 '14 at 09:02
  • Ok, so `String.toCharArray()` is also a standard function. How do you do it without that huh? ;) – lance-java Mar 04 '14 at 09:02
  • 1
    @LanceJava: Yes, but there's a hierarchy. I would assume `System.out.print` would be fine, but `String#split` wouldn't be. Just a feel. I don't know where `toCharArray` would be on that spectrum, compared to `charAt` for instance. – T.J. Crowder Mar 04 '14 at 09:03
  • 1
    @LanceJava You can do very well without `toCharArray`. All you need is `charAt`. – Marko Topolnik Mar 04 '14 at 09:04
  • Ok, so you'd need `String.length()` and `String.charAt()`. Aren't these standard functions too? – lance-java Mar 04 '14 at 09:05
  • I think a function is a method that performs some form of task...like Arrays.sort(). length() and charAt() seem to more like accessors. – Solace Mar 04 '14 at 09:06
  • @LanceJava - See. By "not using standard functions" , the OP means - "don't use functions that make the problem very simple. length, toCharArray() etc are allowed because they don't directly affect the problem's complexity but split() will reduce the problem's complexity substantially." – TheLostMind Mar 04 '14 at 09:10
0

Brute forced this so hard lol

 public static void main (String args[]){       
    String input = new Scanner(System.in).nextLine();
    input+=" ";
    ArrayList<String> words = new ArrayList<String>();
    int start = 0;

    for(int i=0; i<input.length(); i++){
        if(input.charAt(i)==' '){
            String toAdd="";
            for(int r=start; r<i; r++){
                toAdd+=input.charAt(r);
            }
            words.add(toAdd);
            start = i+1;
        }
    }

    for(int i=words.size()-1; i>=0; i--){
        System.out.print(words.get(i)+" ");
    }


 }
Solace
  • 2,161
  • 1
  • 16
  • 33
0

I've used String.length() and String.substring()and String.charAt() - I hope that is allowed.

private static class Word {

    private final String message;
    private final int start;
    private final int end;

    public Word(String message, int start, int end) {
        this.message = message;
        this.start = start;
        this.end = end;
    }

    @Override
    public String toString() {
        return message.substring(start, end);
    }
}

private Word[] split(String message) {
    // Split it into words - there cannot be more words than characters in the message.
    int[] spaces = new int[message.length()];
    // How many words.
    int nWords = 0;
    // Pretend there's a space at the start.
    spaces[0] = -1;
    // Walk the message.
    for (int i = 0; i < message.length(); i++) {
        if (message.charAt(i) == ' ') {
            spaces[++nWords] = i;
        }
    }
    // Record the final position.
    spaces[++nWords] = message.length();
    // Build the word array.
    Word[] words = new Word[nWords];
    for (int i = 0; i < nWords; i++) {
        words[i] = new Word(message, spaces[i] + 1, spaces[i + 1]);
    }
    return words;
}

private String reverse(String message) {
    Word[] split = split(message);
    String reversed = "";
    for ( int i = split.length - 1; i >= 0; i--) {
        reversed += split[i].toString();
        if ( i > 0 ) {
            reversed += " ";
        }
    }
    return reversed;
}

public void test() {
    String message = "Hello how are you today?";
    System.out.println(reverse(message));
}

prints

today? you are how Hello
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

Much more minimal but less useful. Only uses length, charAt and substring again:

public void printWordsReversed(String message) {
    int end = message.length();
    for ( int i = end - 1; i >= 0; i--) {
        if ( message.charAt(i) == ' ') {
            System.out.print(message.substring(i+1, end)+" ");
            end = i;
        }
    }
    System.out.print(message.substring(0, end));
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
-1

The only function i'm still using is the IndexOf function, but that is not that hard to create for yourself.

static void Main(string[] args)
{
    string sentence = "are you cracy";

    int length = Program.StringLength(sentence);

    int currentpos = 0;

    List<string> wordList = new List<string>();

    int wordCount = 0;
    while (currentpos < length)
    {
        // find the next space
        int spacepos = sentence.IndexOf(' ', currentpos);

        string word;

        if (spacepos < 0)
        {
            // end of string reached.
            word = sentence.Substring(currentpos, length - currentpos);
            wordList.Add(word);
            wordCount++;

            // no need to continue.
            break;
        }

        word = sentence.Substring(currentpos, spacepos - currentpos);
        wordList.Add(word);
        wordCount++;

        currentpos = spacepos + 1;
    }

    // display
    for (int i = wordList.Count - 1; i >= 0; i--)
    {
        // after first word is display, add spaces to the output
        if (i < wordList.Count - 1)
        {
            Console.WriteLine(" ");
        }

        // display word
        Console.WriteLine(wordList[i]);
    }
}

public static int StringLength(String sentence)
{
    int numberOfChars = 0;

    while (!sentence.Equals(""))
    {
        sentence = sentence.Substring(1);
        ++numberOfChars;
    }

    return numberOfChars;
}
Pakspul
  • 648
  • 5
  • 17