How to create a random word picker method [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm really new to java and just learning. I'm doing a java assignment and I don't quite understand; I am supposed to create a method that will take in a String array and return a randomly selected Sting from that array. here are the exact instructions:
*getRandomWord --> consumes an array of Strings and selects
(returns) one of the words at random.
signature: String getRandomWord (String [] array)
*
Then I think I have to create another method. I doubt an you have two methods named the same thing but the instructions say:*getRandomWord --> consumes an array of Strings and an integer (len).
This method selects a word from the array whose
length is more than len. If the length of the word
selected is less than len, then this method selects
another word at random. This is repeated 500 times
until a word is found/returned or no word is found
in which case this method will return null.
signature: String getRandomWord (String [] array, int len)
*
As I said I'm really new so help is appreciated.

Since this is an assignment I will only give you pointers to write the method yourself. The algorithm to use in String getRandomWord (String [] array)is elucidated below:
Calculate the length of the array. See How to find length of a string array
Generate the index of the random word from the array's length. See Getting random numbers in java
Get and return the random word from the array.
All these should be done in not more than 3 lines of code. Good Luck!

I would suggest to do it yourself. If you don't get, code is here :) Use the Random API. nextInt() method of Random method gives the Random value, which can be used as index to return random String from Arra.
Below is complete code of 2 methods:
import java.util.Random;
public class TestJava {
public static void main(String[] args) {
String[] strArray = { "first", "second", "third" };
System.out.println(getRandomWord(strArray));
}
static String getRandomWord(String[] array) {
Random random = new Random();
int index = random.nextInt(array.length);
return array[index];
}
static String getRandomWordWithLength(String[] array, int len) {
Random random = new Random();
for (int i = 0; i < 500; i++) {
int index = random.nextInt(3);
String selectedString = array[index];
if (selectedString.length() > len)
return selectedString;
}
return null;
}
}

Try to do yourself at first as it is an assignment. Take help from the code below if you failed it to do yourself.
private String getRandomWord(String[] array) {
int idx = new Random().nextInt(array.length);
return (array[idx]);
}
private String getRandomWord(String[] array, int len) {
String word = null;
for (int i = 1; i <= 500; i++) {
word = getRandomWord(array);
if (word.length() > len) {
break;
} else {
word = null;
}
}
return word;
}

Related

Separating a String to an Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How can i seperate this String:
"thisisanexampleforthisproblemicantsolvetestes"
To this array:
{"thisi","sanex","ampl","efor","this","prob","lemi","cant","solv","etes","tes"}
I want to seperate the first 10 letters in the String into 2 elemnts in an array and the rest should be every 4 letters, to one elemnt in an array.
I hope you can help me. I tried this all day but still didnt solve it
Assuming your input string length >= 10 you can do something like below using streams:
String str = "thisisanexampleforthisproblemicantsolvetestes";
String[] splited = Stream.of(str.substring(0, 10).split("(?<=\\G.{5})"),
str.substring(10).split("(?<=\\G.{4})"))
.flatMap(e -> Arrays.stream(e))
.toArray(String[]::new);
System.out.println(Arrays.toString(splited));
where the regex "(?<=\\G.{n})" is used to split a string at each nth char
More simple to understand:
Results in: thisi, sanex, ampl, efor, this, prob, lemi, cant, solv, etes, tes
public static List<String> strangeThingsDo(String str)
{
List<String> li = new ArrayList<>();
int len = str.length();
if (len <= 5)
{
li.add(str);
return li;
}
if (len <= 10)
{
li.add(str.substring(0,5));
li.add(str.substring(5));
return li;
}
li.add(str.substring(0,5));
li.add(str.substring(5,10));
String s,rest = str.substring(10);
int restlen = rest.length();
int end = 0;
for (int i = 0; i < restlen;i += 4)
{
end = i + 4;
if (end > restlen)
{ s = rest.substring(i);
li.add(s);
break;
}
s = rest.substring(i,end);
li.add(s);
}
System.out.println("---: " + li );
return li;
}
The following code will show you how to split a string by numbers of characters. We create a method called splitToNChars() that takes two arguments. The first arguments is the string to be split and the second arguments is the split size.
This splitToNChars() method will split the string in a for loop. First we’ll create a List object that will store parts of the split string. Next we do a loop and get the substring for the defined size from the text and store it into the List. After the entire string is read we convert the List object into an array of String by using the List‘s toArray() method.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SplitStringForEveryNChar {
public static void main(String[] args) {
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(Arrays.toString(splitToNChar(text, 3)));
System.out.println(Arrays.toString(splitToNChar(text, 4)));
System.out.println(Arrays.toString(splitToNChar(text, 5)));
}
private static String[] splitToNChar(String text, int size) {
List<String> parts = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += size) {
parts.add(text.substring(i, Math.min(length, i + size)));
}
return parts.toArray(new String[0]);
}
}

Scrambling characters of String

public class WordScrambleEx1 {
public static void main(String[] args) {
String[] strArr = {"CHANGE", "LOVE", "HOPE", "VIEW"};
String answer = getAnswer(strArr);
String question = getScrambledWord(answer);
System.out.println("Question :" + question);
System.out.println("Answer: " + answer);
}
public static String getAnswer(String[] strArr) {
String i = strArr[(int)Math.random()*4];
return i;
}
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = null;
for(int i = 0; i < character.length; i ++)
{
char[] java = new char [(int)Math.random()*i] ;
question1 = new String(java);
}
return question1;
}
}
I am very new to Java and was given a question where I am given four letters of words and my method needs to pick one of them randomly using Math.random and scramble the characters of that string.
My code finds a String from the given array but does not scramble the string. Can anyone tell me what I am doing wrong?
Understanding constructor and scope is really hard.
first mistake:
(int) Math.random() * i
will always return 0, because Math.random() returns a float between 0 and 1, so it will always be zero when you cast it to int (int doesnt round, it just cuts off the numbers after the comma).
you can fix this by using this:
(int) (Math.random() * i)
now we are first multiplying the float result of Math.random() with i which results in a float because the first number is a float. then we are casting this float to an int.
second mistake:
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = null;
for(int i = 0; i < character.length; i ++)
{
char[] java = new char [(int)Math.random()*i] ;
question1 = new String(java);
}
return question1;
}
each iteration you create a new char array with a length of 0 and then you set question1 to it, which is always an empty string because the java array has nothing in it.
i would do it as follows:
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = new String();
ArrayList<Character> chars = new ArrayList<Character>(); //an arraylist is an array wich dynamically changes its size depending on the amount of its elements
for (int i = 0; i < character.length; i++) {// first we put all characters of the word into that arraylist
chars.add(character[i]);
}
while(chars.size()>0){//then we iterate over the arraylist as long as it has more than 0 elements
int index = (int)(Math.random() * chars.size());//we create a random index in the range of 0 and the arraylists size
question1 += chars.get(index);// we add the letter at the index we generated to the scrambled word variable
chars.remove(index);// then we remove the character we just added to the scrambled word, from the arraylist, so it cant be in there twice
}// thus the size decreases by 1 each iteration until every element of the arrraylist is somewhere in the scrambled word
return question1;
}
There are some mistakes in your code. The way you generate random integers is misleading. Let's look at the statement (int)Math.random() * 4 for an explanation. Math.random() does:
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Now, in Java a type cast has precedence over +, -, * and /, so what actually happens is ((int)Math.random()) * 4. Math.random() returns a floating point number between 0.0 and 1.0 exclusive, so roughly [0.0, 0.999999...]. A cast to int will truncate all decimal places and you will always get 0. Your statement then simplifies to 0 * 4 = 0. Overall, you always get the first word.
I recommend you to use the Random class instead. It provides a method nextInt(int n), which returns a random integer between 0 inclusive and n exclusive, so [0, n - 1].
Since there are a lot of errors in your code, I would like to provide you this solution:
import java.util.Random;
public class WordScrambleEx1 {
private static Random random;
public static void main(String[] args) {
// Create object of class (initializes the
// random generator with a default seed)
random = new Random();
String[] strArr = { "CHANGE", "LOVE", "HOPE", "VIEW" };
String answer = getAnswer(strArr);
String question = getScrambledWord(answer);
System.out.println("Question: " + question);
System.out.println("Answer: " + answer);
}
public static String getAnswer(String[] strArr) {
// Chooses a random index in [0, strArr.length - 1]
int index = random.nextInt(strArr.length);
String i = strArr[index];
return i;
}
public static String getScrambledWord(String str) {
String remaining = str;
String scrambled = "";
// Loop over the string, each time choose a random letter
// and add it to the scrambled word, then remove that letter
// from the remaining word. Repeat until all letters are gone.
for (int i = str.length(); i > 0; i--) {
// Choose the index of a letter in the remaining string
int index = random.nextInt(remaining.length());
// Add the letter at the random index to your scambled word
scrambled += remaining.charAt(index);
// Remove the chosen character from the remaining sequence
remaining = remaining.substring(0, index) + remaining.substring(index + 1);
}
return scrambled;
}
}

Java Method for removing duplicates from char array

I have a char array filled by the user (arrayInput[]) with some characters, like {b, d, a, b, f, a, g, a, a, f}, and I need to create a method which returns a new char array with only the first occurrence of the character, but in the order of input. The book also says "A way to solve this problem is to create a boolean array to keep track of the characters to mantain!", but I can't imagine how the boolean array should work with the other arrays.
The main problem is that I can save in a boolean array if arrayInput contains a specific character, and even how many times, but only creating a very long ramified if-else into a for, like
if ((arrayOutput[i] == 'A') && (arrayControl[0] = false)) {
arrayControl[0] = true; }
where arrayOutput is the array I want to return from the method, arrayControl[0] is the value of 'A' in my boolean array I created into the method. A = 0, B = 1, ... Z = 25, a = 26, b = 27, ... 51 = z. For every single character, uppercase and lowercase, I created a place into the array, so I could check everything, but now I can't go any further. I don't know how to save the characters on arrayOutput, how to check if a character is already on arrayOutput and if it's already there, the array passes that specific character and go to the next one.
Also please remember I'm a newbie, so I know very little about Java. Please explain yourself the best you can. Thanks in advance!
This could work:
public static void main(String[] args) {
Main main = new Main();
char[] array = {'e','a','b','a','c','d','b','d','c','e'};
main.getCharArray(array);
}
private char[] getCharArray(char[] array) {
String _array = "";
for(int i = 0; i < array.length; i++) {
if(_array.indexOf(array[i]) == -1) // check if a char already exist, if not exist then return -1
_array = _array+array[i]; // add new char
}
return _array.toCharArray();
}
Output:
eabcd
boolean arr[26]; //considering only small letters arrive. otherwise take a larger array.
for( i=0;i<str.length;i++ )
arr[str[i]-'a']=true;
The ones at last after the loop are true are the actual character. (all duplicates eleminated).
To take into consideration the positions,
int arr[26];
//initialize all the array elemnts to 0
for( i=0;i<str.length();i++ )
if(i>=arr[str[i]-'a'])
arr[str[i]-'a']=i+1;
//Those greater than 0 are non-duplicated characters. Their poistion of first occurence= (arr[i]-1)
EDIT: I have last used java almost a year ago. The algorithm is shown properly. Sorry for my awkward java code.
This might help. Make a separate array and store only non-duplicate characters.
char[] removeDuplicates (char[] arrayInput) {
boolean exists[]=new boolean[26];
char arrayOutput[] = new char[26];
int ctr=0;
for(int i=0; i<26; i++) {
exists[i] = false;
}
for(int i=0; i<arrayInput.length; i++) {
if(!exists[arrayInput[i]-97]) {
exists[arrayInput[i]-97]=true;
arrayOutput[ctr++]=arrayInput[i];
}
}
return Arrays.copyOfRange(arrayOutput, 0, ctr);
}
If you consider using of collection framework then it would be much easier. Your array of char with duplicate is arrayInput. Now put each char from it to a HashSet like this -
HashSet<Character> uniqueCharSet = new HashSet<Character>();
for(char each : arrayInput){
uniqueCharSet.add(each);
}
Now the HashSet uniqueCharSet will contains only the unique characters from the char array arrayInput. Note here all element in uniqueCharSet are wrapper type - Character.
You can convert the HashSet uniqueCharSet to array of Character like this -
Object[] uniqueCharArray = uniqueCharSet.toArray();
And then you can use them like this -
for(Object each : uniqueCharArray){
Character c = (Character) each;
System.out.println(c);
}
Here's the method to achieve what you need:
public static void main(String[] args) {
char[] arr= {'A','B','C','A','B'};
HashSet<Character> hset=new HashSet<Character>();
for(int i=0;i<arr.length;i++) {
hset.add(arr[i]);
}
Object[] ObjChar=hset.toArray();
char[] resultArr = new char[ObjChar.length];
for(int j=0;j<ObjChar.length;j++) {
resultArr[j]=(char) ObjChar[j];
}
for(char eachChar: resultArr) {
System.out.println(eachChar);
}
}

String of Number with comma [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having issues when solving this problem:
Write a structures program that can accept two integer numbers up to 40 digit and perform the following:
add the two numbers together and display the result
the result number should should be seperated by commas.
So I was able to do number 1 using BigInteger, but for part 2 I am having issues. I don't know how I'm supposed to add a comma to a string, I was using a for loop to do with split but its not working.
I was able to figure it out thanks for all the help
public static String NewString (String num)
{
String sent = "" ;
int count = 0;
for ( int index = num.length()-1 ; index >= 0 ; index --)
{
count++;
sent = num.charAt(index) + sent;
if(count % 3 == 0 && index != 0)
sent = "," + sent;
}
return sent;
}
You can use
String formattedInteger = NumberFormat.getNumberInstance(Locale.US).format(bigInteger);
or you can write your own. It would be pretty simple, just convert your BigInteger to a String then loop through it backwards and every 3rd character you pass add a comma.
The code below -
Adds two numbers together and displays the result
The result number should be separated by commas.
Is quite self explanatory, Hope this helps :)
package stackoverflow;
import java.math.BigInteger;
/**
* Created by Nick on 11/13/14.
*
* Add two numbers together and display the result
* The result number should be separated by commas.
*/
public class SO_26916958 {
private static BigInteger arg1;
private static BigInteger arg2;
public static void main(String[] args) {
arg1 = new BigInteger (args[0].getBytes());
arg2 = new BigInteger (args[1].getBytes());
BigInteger sum = arg1.add(arg2);
String bigIntegerString = sum.toString();
String output = recursivelyAddComma(bigIntegerString);
System.out.print(bigIntegerString +"\n");
System.out.print(output);
}
private static String recursivelyAddComma (String s) {
int length = s.length();
StringBuilder output = null;
if(length <= 3) {
return s.toString();
}
return recursivelyAddComma(s.substring(0, length - 3)).concat(",").concat(s.substring(length - 3, length));
}
}

ArrayList Confusion and assistance! [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
basically id like a few hints or tips on how to solve this question.. maybe a few things which i could read up on about arraylists and loop which would make it simple for me to understand!..
the question is :
Processing an ArrayList of Characters:
cList is an ArrayList of objects of type Character that has been declared and intialised. Write a loop that will count the Characters that are not spaces and print the number out to the terminal window.
and second question would be:
Looping through a String
Assuming that a variable has been declared like this:
String s;
and that a value has already been assigned to s, write a loop statement that will print the characters of s in reverse order (so if s = "HELLO", your loop should print "OLLEH").
for the first question i tried to do:
public ArrayList()
public static void main(String[] args) {
int countBlank;
char ch;
public ArrayList (int cList)
{
int cList = ;
while(cList ){
System.out.println(cList);
}
}
and second question :
i have no idea, but a read up would be great!
thank you!
You could start by reading up on ArrayList Javadoc and documentation on mindprod.
In your example you haven't declared cList as arraylist nor filled it with Character objects. Instead of a while you might look into for. To get the characters in a String, String.toCharArray() might be of use.
For your first question, you want to loop through the list and count the number of times a character isn't a space.
int counter = 0;
for (Character c : characters) {
if (c == null {
continue; // Note: You can have null values in an java.util.ArrayList
}
if (!Character.isSpaceChar(c)) {
counter++;
}
}
System.out.println(counter);
For your second question:
for (int i = s.length() - 1; i >= 0; i--) {
System.out.print(s.charAt(i));
}
An arraylist is probably too fat for that:
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class CI {
private static final String text = "Hello";
public static void main(String[] args) {
CharacterIterator it = new StringCharacterIterator(text);
for (char ch = it.last(); ch != CharacterIterator.DONE; ch = it
.previous()) {
System.out.print(ch);
}
}
}
Answer to Question 1:
import java.util.*;
public class ProcessListOfChars{
public static int printCharsInListIgnoreSpaces(List<Character> cList){
int count =0;
for(Character character:cList){
// System.out.println("Value :"+character);
if(character!=null &&!character.toString().trim().equals("")){
++count;
}
}
return count;
}
public static void main(String... args){
List<Character> cList = new ArrayList<Character>();
cList.add('c'); //Autoboxed char to Charater Wrapper Class
cList.add(' '); //Space character
cList.add('r');
cList.add('b');
cList.add(' ');
int count = printCharsInListIgnoreSpaces(cList);
System.out.println("Count of Characers :"+count);
}
}

Categories

Resources