I need a String array with the following attributes:
4 digits numbers
No repeating digits ("1214" is invalid)
No 0's
Is there an easier way to do this than manually type it? Like:
String[] s = {"1234","1235",1236",1237",1238",1239","1243","1245"};
Sorry for my English!
The following code will generate an array with your specifications.
public class Test {
public static void main(String[] args) {
List<String> result = new ArrayList<>();
Set<Character> set = new HashSet<>();
for (int i = 1234; i <= 9876; i++) {
set.clear();
String iAsString = Integer.toString(i);
char[] chars = iAsString.toCharArray();
boolean valid = true;
for (char c : chars) {
if (c == '0' || !set.add(c)) {
valid = false;
break;
}
}
if (valid) {
result.add(iAsString);
}
}
String[] yourStringArray = result.toArray(new String[result.size()]);
System.out.println(Arrays.toString(yourStringArray));
}
}
****edit****
Just saw that it is in Java. So use this function: String.valueOf(number) to convert integer to string if none of the digits are repeats in the loop.
Not sure what language you are doing but I am assuming no repeats not replies.
So what you can do is have a loop from 0 to 9999 and then run through all the numbers while checking if each digit has repeats if so discard number (do not store it into array).
You can convert integers to strings in many languages in their function so you can do that then store it into array.
Good luck.
Hope this helped (fastest solution from my head...there could be more efficient ones)
Try this method for creating Random number with your structure :
ArrayList<Integer> rawNumbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
public String createRandomNumberSring()
{
String result = "";
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(rawNumbers);
for(int i = 0; i < 4; i++)
{
int index = (int)(Math.random() * (numbers.size() + 1));
result += numbers.get(index).toString();
numbers.remove(index);
}
return result;
}
Related
Here is an example String, which contains 2 delimiters used for parsing the String to integers:
"1,25,3-6,14,16-19"
The integers in the aforementioned string have to be parsed and added to ArrayList cotaining integers. So the ArrayList has to contain:
1,3,4,5,6,14,16,17,18,19,25
The values in the original string are never mentioned twice. So, there are no crossing sections. Below you can see the incomplete code I wrote so far, but I think that I'm going in a completely wrong direction and there should be an easier way to solve the parsing.
List<Integer> temp = new ArrayList<>();
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] strCh = str.toCharArray();
for (int j = 0; j < strCh.length; j++) {
char c = strCh[j];
String number = "";
char operator = 'n';
if (Character.isDigit(c)) {
do {
number += c;
j++;
if (j != strCh.length - 1)
c = strCh[j];
} while (j < strCh.length && Character.isDigit(c));
} else if (c == ',') {
operator = ',';
temp.add(Integer.parseInt(number));
number = "";
} else if (c == '-') {
//still not sure
}
}
You can use String#split() twice to handle your input string. First split by comma, which leaves us with either an individual number, or an individual range of numbers. Then, in the case of range, split again by dash to obtain the starting and ending numbers of that range. We can iterate over that range, adding each number to our list.
String input = "1,25,3-6,14,16-19";
String[] parts = input.split(",");
List<Integer> list = new ArrayList<>();
for (String part : parts) {
if (part.contains("-")) {
String[] range = part.split("-");
int start = Integer.parseInt(range[0]);
int end = Integer.parseInt(range[1]);
for (int i=start; i <= end; ++i) {
list.add(i);
}
}
else {
int value = Integer.parseInt(part);
list.add(value);
}
}
This generated the following list of numbers:
1,25,3,4,5,6,14,16,17,18,19
Demo here:
Rextester
To ensure there are no duplicates and in order as you expect, use Set:
String inputData = "1,25,3-6,14,16-19";
String[] numberRanges = inputData.split(",");
Set<Integer> set = new TreeSet<>();
for (String numberRange : numberRanges) {
if (numberRange.contains("-")) {
String[] range = numberRange.split("-");
int startIndex = Integer.valueOf(range[0]);
int endIndex = Integer.valueOf(range[1]);
for (int i = startIndex; i <= endIndex; ++i) {
set.add(i);
}
} else {
set.add(Integer.valueOf(numberRange));
}
}
System.out.println(set);
You can try something like this:
String input = "1,25,3-6,14,16-19";
List<Integer> output = new ArrayList<Integer>();
for(String s : input.split(",")){
try{
if(!s.contains("-")){
output.add(Integer.parseInt(s));
}
else{
int i= Integer.parseInt(s.split("-")[0]);
int upperBound = Integer.parseInt(s.split("-")[1]);
for(;i<=upperBound;i++){
output.add(i);
}
}
}catch(NumberFormatException e){
e.printStackTrace();
}
}
Collections.sort(output); // sort the result
System.out.println(output); // test
Output
[1, 3, 4, 5, 14, 16, 17, 18, 19, 25]
Take a look at the StringTokenizer.
Heres my code that takes a string and returns an array of the ascii values for each character in the array in order. Compile error is 'array required, but java.lang.String found'
public class Q1E {
int[] stringToCodes(String characters){
int characterLength= length(characters);
int[] array=new int[characterLength];
for(int i=0;i<characterLength;i++) {
array[i] =(int) characters[i];
}
}
}
You can't use array syntax on a String, use character.charAt(i)instead. Also, you need to return the array at the end.
Java uses Unicode/UTF-16 for strings, not ASCII.
If want to restrict your method to processing characters in the ASCII range, it should throw an exception when it encounters one outside that range.
If you want a sequence of "character codes" (aka codepoints), you have to use the String.codePointAt() at method. Because String holds a counted sequences of UTF-16 code-units and there might be one or two code-units per codepoint, you only know that String.length() is an upper bound of the number of codepoints in advance.
public class Q1E {
int[] stringToCodes(String s) {
int[] codepoints = new int[s.length()]; // there might be fewer
int count = 0;
for(int cp, i = 0; i < s.length(); i += Character.charCount(cp)) {
cp = s.codePointAt(i);
// for debugging, output in Unicode stylized format
System.out.println(String.format(
cp < 0x10000 ? "U+%04X" : "U+%05X", cp));
codepoints[count++] = cp;
}
int[] array = java.util.Arrays.copyOf(codepoints, count);
return array;
}
}
Try it with this Wikipedia link on an English word:
stringToCodes("http://en.wikipedia.org/wiki/Résumé");
Your code appears to have a few bugs, it's String#length() and I would suggest you add a null check. Finally (since characters isn't an array), I think you want to use String#charAt(int)
int[] stringToCodes(String characters) {
int characterLength = 0;
if (characters != null) {
characterLength = characters.length();
}
int[] array = new int[characterLength];
for (int i = 0; i < characterLength; i++) {
array[i] = characters.charAt(i);
}
return array;
}
Of course, you could shorten it with a ternary
int characterLength = (characters != null) ? characters.length() : 0;
int[] array = new int[characterLength];
try this:
public class Test {
public static void main(String[] args) {
int []ascii=stringToCodes("abcdef");
for(int i=0;i<ascii.length;i++){
System.out.println(ascii[i]);
}
}
public static int [] stringToCodes(String characters){
int []ascii=new int[characters.length()];
for(int i=0;i<characters.length();i++){
ascii[i]=(int)characters.charAt(i);
}
return ascii;
}
}
In a recent interview, I was asked this to find the length of the longest sub-string with no consecutive repeating characters. This is different from the standard question, since it considers only consecutive repeating characters.
For example :
WOOD : 2
Italics : 7
This, of course, has to be done in O(N) time and space.
Go down the string character by character. Keep track of how many characters you've advanced without hitting a repeat in a var say "repeatcounter". If the next character matches the current character record the counter in a separate variable (only if it's bigger than what's already in there) and reset the repeatcounter.
In Python, I would approach it like this:
def interview(s):
current = longest = 0
for index, char in enumerate(s):
if index and char == s[index - 1]:
longest, current = max(longest, current), 0
current += 1
return max(longest, current)
public static void main(String[] args){
String s = "italics";
char[] c = s.toCharArray();
int tmp = 1;
for (int i = 1; i < s.length(); i++) {
if (c[i] == c[i-1]){
tmp = 0;
continue;
}
tmp++;
}
System.out.println(tmp);
}
output = 1
s = "italics"
output = 7
Hope the below code helps you. Thanks.
import java.util.HashSet;
public class SubString {
public static String subString(String input){
HashSet<Character> set = new HashSet<Character>();
String longestOverAll = "";
String longestTillNow = "";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (set.contains(c)) {
longestTillNow = "";
set.clear();
}
longestTillNow += c;
set.add(c);
if (longestTillNow.length() > longestOverAll.length()) {
longestOverAll = longestTillNow;
}
}
return longestOverAll;
}
public static void main(String[] args) {
String input = "kaveeshkanwal abcvdghytrqp";//"substringfindout";
System.out.println(subString(input));
}
}
Well, this is my first time get here.
I'm trying to figure out the correct way to replace number into letter.
In this case, I need two steps.
First, convert letter to number. Second, restore number to word.
Words list: a = 1, b = 2, f = 6 and k = 11.
I have word: "b a f k"
So, for first step, it must be: "2 1 6 11"
Number "2 1 6 11" must be converted to "b a f k".
But, I failed at second step.
Code I've tried:
public class str_number {
public static void main(String[] args){
String word = "b a f k";
String number = word.replace("a", "1").replace("b","2").replace("f","6").replace("k","11");
System.out.println(word);
System.out.println(number);
System.out.println();
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
System.out.println(number);
System.out.println(text);
}
}
Result:
b a f k
2 1 6 11
2 1 6 11
b a f aa
11 must be a word "k", but it's converted to "aa"
What is the right way to fix this?
Or do you have any other ways to convert letter to number and vice versa?
Thank you.
It would be good to write methods for conversion between number and letter format. I would write some code like this and use it generally instead of hard coding replace each time.
public class test {
static ArrayList <String> letter = new ArrayList<String> ();
static ArrayList <String> digit = new ArrayList<String> ();
public static void main(String[] args) {
createTable();
String test="b a f k";
String test1="2 1 6 11";
System.out.println(letterToDigit(test));
System.out.println(digitToLetter(test1));
}
public static void createTable()
{
//Create all your Letter to number Mapping here.
//Add all the letters and digits
letter.add("a");
digit.add("1");
letter.add("b");
digit.add("2");
letter.add("c");
digit.add("3");
letter.add("d");
digit.add("4");
letter.add("e");
digit.add("5");
letter.add("f");
digit.add("6");
letter.add("g");
digit.add("7");
letter.add("h");
digit.add("8");
letter.add("i");
digit.add("9");
letter.add("j");
digit.add("10");
letter.add("k");
digit.add("11");
letter.add("l");
digit.add("12");
letter.add("m");
digit.add("13");
letter.add("n");
digit.add("14");
letter.add("o");
digit.add("14");
letter.add("p");
digit.add("15");
//Carry so on till Z
}
public static String letterToDigit(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(letter.contains(individual[i])){
result+=Integer.toString(letter.indexOf(individual[i])+1)+ " ";
}
}
return result;
}
public static String digitToLetter(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(digit.contains(individual[i])){
result+=letter.get(digit.indexOf(individual[i])) + " ";
}
}
return result;
}
}
I would actually not use replace in this case.
A more generic solution would be to simply convert it to a char and subtract the char a from it.
int n = word.charAt(0) - 'a' + 1;
This should return an int with the value you are looking for.
If you want this to be an string you can easily do
String s = Integer.parseInt(word.charAt(0) - 'a' + 1);
And as in your case you are doing a whole string looping through the length of it and changing all would give you the result
String s = "";
for(int i = 0; i < word.length(); i++) {
if(s.charAt(i) != ' ') {
s = s + Integer.toString(word.charAt(i) - 'a' + 1) + " ";
}
}
and then if you want this back to an String with letters instead
String text = "";
int temp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' ') {
text = text + String.valueOf((char) (temp + 'a' - 1));
temp = 0;
} else if {
temp = (temp*10)+Character.getNumericValue(s.charAt(i));
}
}
You can just reverse the replacement:
String text = number.replace("11","k").replace("2","b").replace("6","f").replace("1","a");
Simplest solution IMO.
When adding other numbers, first replace these with two digits, then these with one.
Replace this:
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
By this:
String text = number.replace("11","k").replace("1", "a").replace("2","b").replace("6","f");
Right now, the first replace you're doing: ("1", "a")
is invalidating the last one: ("11","k")
I think you would need to store the number as an array of ints. Otherwise, there is no way of knowing if 11 is aa or k. I would create a Map and then loop over the characters in the String. You could have one map for char-to-int and one for int-to-char.
Map<Character,Integer> charToIntMap = new HashMap<Character,Integer>();
charToIntMap.put('a',1);
charToIntMap.put('b',2);
charToIntMap.put('f',6);
charToIntMap.put('k',11);
Map<Integer,Character> intToCharMap = new HashMap<Integer,Character>();
intToCharMap.put(1,'a');
intToCharMap.put(2,'b');
intToCharMap.put(6,'f');
intToCharMap.put(11,'k');
String testStr = "abfk";
int[] nbrs = new int[testStr.length()];
for(int i = 0; i< testStr.length(); i++ ){
nbrs[i] = charToIntMap.get(testStr.charAt(i));
}
StringBuilder sb = new StringBuilder();
for(int num : nbrs){
sb.append(num);
}
System.out.println(sb.toString());
//Reverse
sb = new StringBuilder();
for(int i=0; i<nbrs.length; i++){
sb.append(intToCharMap.get(nbrs[i]));
}
System.out.println(sb.toString());
This failed because the replace("1", "a") replaced both 1s with a characters. The quickest fix is to perform the replace of all the double-digit numbers first, so there are no more double-digit numbers left when the single-digit numbers get replaced.
String text = number.replace("11","k").replace("1", "a").
replace("2","b").replace("6","f");
First off I want to start by saying I'm not just looking for someone to give me the answer to this problem, I am a beginner programmer and am just trying to learn as much as possible. A critique of my code and a friendly nudge in the right direction would be most appreciated! What is really confusing me is my stringParser method. I use this method to loop through the string, picking out the numbers and storing them in a new string to be parsed. What confuses me is how I would be able to add these numbers together? Here is the code:
public static int stringParser(String parsee,int parsed)
{
int indexOfString = parsee.indexOf("="); //Searches for an = sign since there has to be one
String parsee2 = "";
int [] newArray;
String subStringParse = parsee.substring(0,indexOfString); //Substring made to divide string, this one is from 0 index to 1st occurence of =
for(int i = 0;i<subStringParse.length();i++)
{
if(Character.isDigit(subStringParse.charAt(i))) //if the value is a number it is stored in a new string then parsed.
{
parsee2+= subStringParse.charAt(i);
parsed = Integer.parseInt(parsee2);
}
} return parsed;
}
public static int sumInts(int a,int storedSums)
{
//a = new int[20];
for(int i=0;i<a;i++) //loops through parsed string from stringParser
{
storedSums += a; //creates a new value calculating sum
}
return storedSums;
}
As per my guess, you want to parse something like this `12 + 34 = '.
If I'm right, then your for loop is completely wrong. It will return only 34 as integer value. You can debug your code for that.
I suggest you something like this :
int index = 0;
for(int i = 0;i<subStringParse.length();i++)
{
if(Character.isDigit(subStringParse.charAt(i))) //if the value is a number it is stored in a new string then parsed.
{
parsee2+= subStringParse.charAt(i);
parsed = Integer.parseInt(parsee2);
}
newArray[index++] = parsed; //make sure you initialize newArray.
}
return newArray;
Try,
String parsee = "12+13 = 34+45 = 45+-45";
int value = 0;
String parsed = "";
for(String exp : parsee.split("=")){
for(String val : exp.trim().split("\\+")){
value+=Integer.parseInt(val);
}
parsed+=" SUM = "+value;
value = 0;
}
System.out.println(parsed);
Output
SUM = 25 SUM = 79 SUM = 0