In java.
It should use the random number generator to return a randomly chosen substring of text that has the specified length. If the length is either negative or greater than the length of text, the method should throw an IllegalArgumentException. For example, chooseSubstring("abcde", 4, new Random()) should return "abcd" about half the time and "bcde" about half the time.
public static String chooseSubstring (String text, int length, Random rand)
{
int randomNum = rand.nextInt(length);
String answer = text.substring(randomNum);
return answer;
}
Basically, I want to return a substring from the variable text. The substring must be the length of the variable length. The beginning of this substring should start at a random location determined by a random number generator. My problem is that the random number generator is not making sure the substring is the correct length.
System.out.println(chooseSubstring("abcde", 4, new Random()));
Should return abcd and bcde about the same amount of times. Instead it is returning:
bcde
cde
de
abcde.
Any info about how to solve this would greatly help thanks!
Your code is taking a substring at a random index between 0 and length, exclusive. You have to specify the end index so it doesn't extend to the end of the string. You also need to reduce the range of the starting index so the end index doesn't go past the string:
int randomNum = rand.nextInt(text.length() - length + 1);
String answer = text.substring(randomNum, randomNum + length);
Related
I have to make an array that contains random numbers in certain range, but each number has to contains same digits as number n (user input).Also numbers can be duplicated. For example n=11452 so the generated number can be 221545. Every next number has to contain 1,4,5,2(in this case where n is 11452) I just need an idea for solving this.
1) Determine the number of distinct digits in the user input (in your example 4: 1,2,4,5)
2) Create a random number of at least this number of digits (in your example: at least 1000)
3) Insert the requested digits in random positions of the found number. Make sure these positions are distinct. I.e., make sure no requested digit is overwritten by another one.
Does this make sense?
1) Parse the user input number as String and add all digits to a Set.
2) Convert your set to an array to have access to random index of array.
3) Access the parsed digits in the converted array via random index.
Perhaps, this is not a perfect implementation but the following method will generate a random digit which follows your requirements as i understood. The length of the generated random digit is so long as your user input number.
Just modify it to create an array with generated random numbers as your requirements.
public int generate(String number) throws NumberFormatException {
// 1) parse number and add the digits to a set
HashSet<Integer> digits = new HashSet<>();
for (String digitStr : number.split("")) {
int digit = Integer.parseInt(digitStr);
digits.add(digit);
}
// 2) convert the set to array to access via random index
Integer[] digitArray = new Integer[number.length()];
digits.toArray(digitArray);
String generated = "";
Random random = new Random();
for (int i=0; i < number.length(); i++) {
// 3) grap a random digit from array and append it to your result
int randomIndex = Math.abs(random.nextInt()) % number.length();
generated += digitArray[randomIndex];
}
return Integer.parseInt(generated);
}
This is part of a longer coding challenge - one part involves "flipping" the digits of an input number (i.e. 1234 becomes 4321) and removing leading zeros as applicable.
Below, I have written the method flipOpp that accomplishes this. Most of the time, it works perfectly. But sometimes, I'm getting an error because the last digit becomes a dash ("-") and obviously, the Integer.parseInt() method won't work if one of the digits is a dash!
Any ideas what might be causing this? Also, is there an easier way to flip the digits of an int? The method I'm using right now doesn't seem very efficient - turning an int to a String, then to a character array, manipulating the characters of this array, turning it back into a String, and finally back to an int.
Thanks! Code for this method is below:
// third operation: reverse the digits and remove leading zeros
public static int flipOpp(int num){
char temp;
// change int to a String
String stringNum = Integer.toString(num);
// change String to a char array of digits
char[] charNum = stringNum.toCharArray();
// flip each character and store using a char temp variable
for (int i=0;i<charNum.length/2;i++){
temp = charNum[i];
charNum[i]=charNum[charNum.length-i-1];
charNum[charNum.length-i-1]=temp;
}
// turn flipped char array back to String, then to an int
// this process removes leading zeros by default
String flipString = new String(charNum);
if (flipString.length()<7){
int flipInt = Integer.parseInt(flipString);
return flipInt;
}
else return 0;
}
Any ideas what might be causing this?
Definitely sounds like negative numbers
is there an easier way to flip the digits of an int? The method I'm using right now doesn't seem very efficient
Keep it as an integer. Don't worry about the negative
public static int flipOpp(int num) {
int reversed = 0;
while (num!=0) {
reversed = reversed*10 + num%10;
num /= 10;
}
return reversed;
}
For example, -50,
0*10+0=0
-50/10=-5
- -
0*10+(-5)=-5
-5/10=0
- -
END, output -5
here i have a problem. i want a user to input some numbers, then i will convert the input into a string,i will then count the length of the string, and if it is less than 8,i want to add more zeros to the input to make it 8 so that i can do some staff with the number. i have tried to use decimalformat but its not working. plz help.
thanks in advance
int s=Integer.parseInt(s1.readLine());
String news=String.valueOf(s);
if(news.length()<8){
DecimalFormat myformat=new DecimalFormat("00000000");
String out= myformat.format(s);
int onth=(Integer.valueOf(out)).intValue();
s=onth;
}else{
System.out.format("your number is: %d\n",s);
Forget about using the DecimalFormat.
Change your format to the following
System.out.format("your number is: %08d\n",s)
The %08d will lead with zeros, to a width of 8.
This will only display the number in the format you've requested. As stated elsewhere in this thread, treating it as a number would remove the leading zeros.
If you want to store it in a String variable however, you can use
String intString = String.format("%08d", s);
to store it.
Update *
As you have a specific need to get a series of numbers between a substring
the following code will do what you want.
private static int getSubNumber(int startIndex, int stopIndex, int number) {
String num = String.format("%08d", number);
return Integer.parseInt(num.substring(startIndex, stopIndex));
}
If you pass in the number you want to convert, it will change it to a string, and then convert the substring between the two indexes you pass in back into a number
System.out.println(getSubNumber(2,5,12345678)); // = 345
System.out.println(getSubNumber(2,5,12345)); // = 12
System.out.println(getSubNumber(2,5,123)); // = 0
This is non inclusive, getSubNumber(2,5,...) gets values at position 2,3 and 4 NOT 5.
For your example of 144, use start index 2, stop index 6 for positions 2, 3, 4 and 5
System.out.println(getSubNumber(2,6,144)); // = 1
DecimalFormat is to format numbers in the way we give the pattern.
And to append zeros, please follow this:
Add leading zeroes to a string
If you need to add 0 after the value, you can multiply it by 10 pow the number of missing 0:
int result = Integer.parseInt(news);
if(news.length()<8){
int diff = 8 - news.length();
result = result * Math.pow(10, diff); // ==> result = result * 10^(8 - news.length())
}
I think that's the simpliest way to do that.
Edit Ahhh, yes... There is prefix in the question. Nevermind!
Even if you prefix an int with zeros the actual value will change to the original value. If you want padding you'll have to go with string. The out variable will give you the result.
Update based on comment
import java.util.Scanner;
public class SquareSubString {
public static void main(String[] args) {
String userInputSquare = getSquaredInput();
int digits2to5 = Integer.parseInt(userInputSquare.substring(2, 6));
System.out.println("Squre of digits 2 to 5 is : " + (digits2to5 * digits2to5));
}
private static String getSquaredInput() {
System.out.println("Enter a number : ");
Scanner in = new Scanner(System.in);
int input = in.nextInt();
in.close();
return String.format("%08d", (input * input));
}
}
I realize permutations in programming language is a very frequently asked question, however I feel like my question is sort of unique.
I have received input of a certain length integer N and stored each digit in an array where the index of the array stores the number of times that digit occurs in N.
now I want to test if some function holds true with all permutations of N's original length with no leading zeroes. Ex:
int[] digits = new int[10];
String n = "12345675533789025";
for (char c : n.toCharArray())
digits[c-'0']++;
for (Long f : allPermutationsOf(digits))
if (someCondition(f))
System.out.println(f);
a precondition to the following code is that N must be less than 2^64-1, (long's maximum value.)
The question is, how would I take all permutations of the digits array and return a Long[] or long[] without using some kind of String concatenation? Is there a way to return a long[] with all permutations of digits[] in the "Integer scope of things" or rather using only integer arithmetic?
To elaborate on one of the above comments, putting a digit d in a given place in the resulting long is easy: d*1 puts it in the 1s place, d*1000 puts it in the thousands place, and in general d * (10^k) puts d into the k+1th digit. You have N total digits to fill, so you need to do permutations on the powers of 10 from 1 to 10^(N-1).
If you are expecting the permutations to be Longs anyway, instead of representing n as an array of counts, it might be easier to represent it as a Long too.
Here are a couple of ways you can generate the permutations.
Think of generating permutations as finding the next largest number with the same set of digits, starting from the number consisting of the sorted digits of n. In this case, the answers to this StackOverflow question is helpful. You can use arithmetic operations and modding instead of string concatenation to implement the algorithm there (I can provide more details if you like). A benefit of this is that the permutations you generate will automatically be in order.
If you don't care about the order of the permutations and you expect the number of digit duplicates to be small, you can use the Steinhaus-Johnson-Trotter algorithm, which (according to Robert Sedgewick) is the fastest algorithm for generating permutations of unique elements. To make sure duplicate permutations are not generated, you would have to distinguish every duplicate digit and only emit the permutations where they appear in order (i.e., if 2 appears three times, then create the elements 2_1, 2_2, 2_3 and make sure those three elements always appear in that order in an emitted permutation).
For the requirement, assuming that the length of N is n, we can generate all permutations by going from digit to digit, starting from 0 and end at n - 1. With 0 is the leading digit.
For each digit, we only go through each possibility (0 to 9) once , which will avoid duplicate permutation.
From digit x to digit x + 1, we can easily generate the current value by passing a number called current
For example: at digit 3, we have current = 1234, so at digit 4, if we choose 5 to be at digit 4, the current will be 1234*10 + 5 = 12345
Sample code in Java:
public void generate(int index, int length, int[] digits, long current, ArrayList<Long> result) {
//All the permutation will be stored in result ArrayList
for (int i = 0; i < 10; i++) {
if (digits[i] > 0 && (i != 0 || index != 0)) {
digits[i]--;
if (index + 1 == length) {//If this is the last digit, add its value into result
result.add(current * 10 + i);
} else {//else, go to next digit
generate(index + 1, length, digits, current * 10 + i, result);
}
digits[i]++;
}
}
}
An aromatic number is of the form AR, where each A is an Arabic digit, and each
R is a Roman numeral.
Each pair AR contributes a value described below, and by adding or
subtracting these values together we get the value of the entire aromatic number.
An Arabic digit A can be 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9. A Roman numeral R is one of the seven letters I, V, X, L, C, D, or M. Each Roman numeral has a base value:
This program is designed to take a AR value on the same line (inputted like e.g. 3V), and multiply it. 3V would be 3 x 5 = 15. Since V is 5.
My issue is that I cannot take what the user inputs and multiply an integer by a string. This makes it tedious. I tried converting the string into a int but the program gives me a nullformatException.
Also A would be in the first cell [0] and R (the numeral) in cell [1]
import java.io.*;
import java.util.*;
import java.text.*;
public class AromaticNumerals
{
public static int decode (String x) // since input is direct the program doesnt require validation
{
if (x.equals ("I"))
return 1;
else if (x.equals ("V"))
return 5;
else if (x.equals ("X"))
return 10;
else if (x.equals ("L"))
return 50;
else if (x.equals ("C"))
return 100;
else if (x.equals ("D"))
return 500;
else
return 1000;
}
public static void main (String str[])
throws IOException
{
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
int Output;
int MAX = 20;
String[] x = new String [MAX]; // by picking an array we can separate the A-R
System.out.println ("Please input an aromatic number. (AR)");
x [0] = (stdin.readLine ());
int y = Integer.parseInt (x [0]);
Output = ( y * decode (x [1]));
System.out.println (Output);
}
}
int MAX = 20;
String[] x = new String [MAX]; // by picking an array we can separate the A-R
Incorrect. All of your input is going into the first element of the array, x[0]. You are confusing an array of strings with an array of characters. The simplest solution is to eliminate the String[] and use a plain String, then extract the individual characters with charAt() or substring().
stdin.readLine() is going to grab all the characters from the console and store them in the string found at x[0]. You're then attempting to parse an integer from the full string, not just the first character, this is why your call to parseInt is failing. Instead, call parseInt on the first character via parseInt(x[0].substring(0,1)) and pass the second character of the string to the decode method via decode(x[0].substring(1,2)). Also, if you don't need an array of strings, don't use one.
Did you by chance come from a C background? Or any other languages where string is a pointer to the first element of an array of characters? Java works differently in that respect, a Java string is first class object so x [0] = (stdin.readLine ()); reads the whole line into the first string so int y = Integer.parseInt (x [0]); will try to parse both A and R. Instead you want perhaps x[0].charAt(0) and x[0].charAt(1), also you don't need x to be an array.
Why you're getting errors:
When you read the user input here
x [0] = (stdin.readLine ());
... you are reading the whole aromatic number e.g. 4V or whatever, and you are putting it in the first index of your array x. Then,
int y = Integer.parseInt (x [0]);
Here you try to parse the first element of x as an integer. But you didn't just put the integer part of the aromatic number there, you put the whole thing. You'll get a NumberFormatException there, because the Integer class can't parse the letter character you're passing it along with the number. Then,
Output = ( y * decode (x [1]));
... you try to pass the second element of x to the decode method, but there's nothing there, because you put the entire string in x[0]. That's your NullFormatException, because x[1] is null.
To fix it:
String line = stdin.readLine();
int y = Integer.parseInt(line.charAt(0));
int output = y * decode(line.charAt(1));
or whatever.