How to print each word from Sentence by Random Indexing - Python/Java

What is the best way to print each word from the Sentence by using random indexing. Tricky String formatting interview coding question-answers.

Problem 1 : Print each word from given the Sentence in random Format : 


 Example  : "The Hungry Dog Jumped Over The Hungry Fox And Killed It"

Java Solution: 
// save this code into the file with name:  Main.java
 
import java.util.LinkedHashSet; import java.util.Random; import java.util.Set; public class Main { public static void main(final String[] args) throws Exception { Random randNum = new Random(); Set<Integer>set = new LinkedHashSet<Integer>(); String s2 = "The Hungry Dog Jumped Over The Hungry Fox And Killed It"; String [] s3 = s2.split("\\s"); int String_Length=s3.length; while (set.size() < String_Length) { set.add(randNum.nextInt(String_Length)); } //System.out.println("Random numbers with no duplicates = "+set); //int i; //for (i = 0; i < s3.length; i++) //System.out.print(s3[i]+" "); for (int s : set) System.out.print(s3[s]+" "); } }

Output:
Hungry Fox It Hungry The And Dog Jumped Over Killed The

Python Solution:

import random

string="The Hungry Dog Jumped Over The Hungry Fox And Killed It".split(" ")
length=len(string)
random_index=random.sample(range(0,length), length)

output= [string[index]  for index in random_index]

#print( [string[i]  for i in random_index])
#print(*output, sep = "\n")
#print(' '.join(map(str, output))) 

print(*output)

Output:
The Hungry The It Jumped And Killed Fox Dog Hungry Over

About the Author

I'm a professor at National University's Department of Computer Science. My main streams are data science and data analysis. Project management for many computer science-related sectors. Next working project on Al with deep Learning.....

Post a Comment

Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.