Friday, August 27, 2021

Program to rearrange words in a sentence (Assessment Test)

 

Rearrange words

Requirement

1) Arrange the words in alphabetical order based on only the "first" character (not the second character and further characters). 

2) If two words are starting with the same character then the same order of the words should be maintained from the original sentence. 

Constraints for this problem

    Use char[] or Character[] array for the input and output. (e.g., avoid in-built java.lang.String or similar class to represent 'string', instead use char[] to solve the problem). 

    e.g.,  Java      :    char input[] = "The domestic dog is a domesticated form of wolf".toCharArray()
             Python      :    input = list('The domestic dog is a domesticated form of wolf')
             Javascript  :   input = Array.from('hello')

Example 1:

Input    :  this is an impossible task

Output :  an is impossible this task

Explanation:

       'a' is the lowest, followed by 'i' and 't' character.
       an - first word because of 'a'
       'is impossible' - 'is' comes before 'impossible' since 'is' appears in the orginial sentence before 'impossible'
       'this task' - 'this' comes before 'task' since 'this' appears in the orginial sentence before 'task'.

Program to rearrange words in a sentence

input_str = "this is an impossible task"

#output = "an is impossible this task"

def sort_strings(list):
    flag = 0
    for index in range(len(arbitrary_list) - 1):  
        if arbitrary_list[index][0] > arbitrary_list[index + 1][0]:
            tmp_word = arbitrary_list[index]
            arbitrary_list[index] = arbitrary_list[index + 1]
            arbitrary_list[index + 1] = tmp_word
            flag = 1
    return flag

arbitrary_list = []

new_word = ""

for letter in input_str:   #the domestic
    if letter.isspace():   # 't', 'h', 'e', ' ', 'd' ..... etc
       print("Space word ... Add new_word to list and comma sep")
       arbitrary_list.append(new_word)  #the
       new_word = ""
    else:
       new_word = new_word + letter   # new_word = 't' + 'h' + 'e'

if new_word:
   arbitrary_list.append(new_word)    

return_value = sort_strings(arbitrary_list)

while sort_strings(arbitrary_list):
   print("Continue sorting ... ")
else:
   print("Sorted list is", arbitrary_list)

Output

Sorted list is ['an', 'is', 'impossible', 'this', 'task']

No comments:

Post a Comment