I want to generate string of given length, from given characters. The order of the characters matters, also I want to use multiple threads to generate it. Here are a few examples:
chars: a,b,c,d
length: 1
output:
a
b
c
d
chars: a,b,c,d
length: 2
output:
aa
ab
ac
ad
bb
ba
bc
bd
cc
ca
cb
cd
dd
da
db
dc
I've tried this algorithm:
Note: it's pseudo-code
func generate(set, str, k){
if (k == 0){
print str;
return;
}
for (c in set) {
newString = str + c;
generate(set, newString, k-1);
}
}
However I don't see how to use multiple threads. All other algorithms I've read about don't suite my needs.
No need of use multithreading for this algorithm. The for loop is only for generating string for required length. In java the code is like this.
import java.util.Random;
public class RandomString2 {
static String[] option = {"a","b","v","k"};
static String getRandomElement()
{
int idx = new Random().nextInt(option.length);
return option[idx];
}
static String getRandomString(int length)
{
String result="";
for(int i = 1; i<=length ; i++)
{
result += getRandomElement();
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(getRandomString(5)); // pass string length as parameter
}
}
Related
I'm trying to multiply some string a by some integer b such that a * b = a + a + a... (b times). I've tried doing it the same way I would in python:
class Test {
static function main() {
var a = "Text";
var b = 4;
trace(a * b); //Assumed Output: TextTextTextText
}
}
But this raises:
Build failure Test.hx:6: characters 14-15 : String should be Int
There doesn't seem to be any information in the Haxe Programming Cookbook or the API Documentation about multiplying strings, so I'm wondering if I've mistyped something or if I should use:
class Test {
static function main() {
var a = "Text";
var b = 4;
var c = "";
for (i in 0...b) {
c = c + a;
}
trace(c); // Outputs "TextTextTextText"
}
}
Not very short, but array comprehension might help in some situations :
class Test {
static function main() {
var a = "Text";
var b = 4;
trace( [for (i in 0...b) a].join("") );
//Output: TextTextTextText
}
}
See on try.haxe.org.
The numeric multiplication operator * requires numeric types, like integer. You have a string. If you want to multiply a string, you have to do it manually by appending a target string within the loop.
The + operator is not the numeric plus in your example, but a way to combine strings.
You can achieve what you want by operator overloading:
abstract MyAbstract(String) {
public inline function new(s:String) {
this = s;
}
#:op(A * B)
public function repeat(rhs:Int):MyAbstract {
var s:StringBuf = new StringBuf();
for (i in 0...rhs)
s.add(this);
return new MyAbstract(s.toString());
}
}
class Main {
static public function main() {
var a = new MyAbstract("foo");
trace(a * 3); // foofoofoo
}
}
To build on tokiop's answer, you could also define a times function, and then use it as a static extension.
using Test.Extensions;
class Test {
static function main() {
trace ("Text".times(4));
}
}
class Extensions {
public static function times (str:String, n:Int) {
return [for (i in 0...n) str].join("");
}
}
try.haxe.org demo here
To build on bsinky answer, you can also define a times function as static extension, but avoid the array:
using Test.Extensions;
class Test {
static function main() {
trace ("Text".times(4));
}
}
class Extensions {
public static function times (str:String, n:Int) {
var v = new StringBuf();
for (i in 0...n) v.add(str);
return v.toString();
}
}
Demo: https://try.haxe.org/#e5937
StringBuf may be optimized for different targets. For example, on JavaScript target it is compiled as if you were just using strings https://api.haxe.org/StringBuf.html
The fastest method (at least on the JavaScript target from https://try.haxe.org/#195A8) seems to be using StringTools._pad.
public static inline function stringProduct ( s : String, n : Int ) {
if ( n < 0 ) {
throw ( 1 );
}
return StringTools.lpad ( "", s, s.length * n );
}
StringTools.lpad and StringTools.rpad can't seem to decide which is more efficient. It looks like rpad might be better for larger strings and lpad might be better for smaller strings, but they switch around a bit with each rerun. haxe.format.JsonPrinter uses lpad for concatenation, but I'm not sure which to recommend.
Lab Description : Compare two strings to see if each of the two strings contains the same letters in the
same order.
This is what I have so far far:
import static java.lang.System.*;
public class StringEquality
{
private String wordOne, wordTwo;
public StringEquality()
{
}
public StringEquality(String one, String two)
{
setWords (wordOne, wordTwo);
}
public void setWords(String one, String two)
{
wordOne = one;
wordTwo = two;
}
public boolean checkEquality()
{
if (wordOne == wordTwo)
return true;
else
return false;
}
public String toString()
{
String output = "";
if (checkEquality())
output += wordOne + " does not have the same letters as " + wordTwo;
else
output += wordOne + " does have the same letters as " + wordTwo;
return output;
}
}
My runner looks like this:
import static java.lang.System.*;
public class StringEqualityRunner
{
public static void main(String args[])
{
StringEquality test = new StringEquality();
test.setWords(hello, goodbye);
out.println(test);
}
}
Everything is compiling except for the runner. It keeps saying that hello and goodbye aren't variables. How can I fix this so that the program does not read hello and goodbye as variables, but as Strings?
You need to quote strings otherwise they are treated as variables.
"hello"
"goodbye"
so this would work better.
test.setWords("hello", "goodbye");
Problem with your code is with checkEquality(), you are comparing the string's position in memory when you use == use .equals() to check the string
public boolean checkEquality()
{
if (wordOne == wordTwo) //use wordOne.equals(wordTwo) here
return true;
else
return false;
}
Enclose them in double-quotes.
I have just started learning Groovy which looks really awesome!
This is very simple example.
"Groovy".each {a -> println a};
It nicely prints as given below.
G
r
o
o
v
y
My question is - 'each' method is not part of String object as per the link below. Then how come it works?
http://beta.groovy-lang.org/docs/latest/html/groovy-jdk/
How can i get the parameters list for a closure of an object?
example String.each has 1 parameter, Map.each has 1 or 2 parameters like entry or key & value.
The relevant code in DefaultGroovyMethods is
public static Iterator iterator(Object o) {
return DefaultTypeTransformation.asCollection(o).iterator();
}
which contains:
else if (value instanceof String) {
return StringGroovyMethods.toList((String) value);
}
String toList is:
public static List<String> toList(String self) {
int size = self.length();
List<String> answer = new ArrayList<String>(size);
for (int i = 0; i < size; i++) {
answer.add(self.substring(i, i + 1));
}
return answer;
}
I have a file for example like this :
file.txt
Milano Tirana Paris
Madrid Istanbul Berlin
And I want to read just the third words of each line Paris and Berlin. I tried with substring but it won't work because the length changes. How can I do it ?
I'd recommend reading the whole line, tokenizing it by splitting it at whitespace, and return the index of the value you want.
Something like this:
package misc;
/**
* CityParser demo
* #author Michael
* #link https://stackoverflow.com/questions/24420434/read-the-third-string-only-java/24420447#24420447
* #since 6/25/2014 8:36 PM
*/
public class CityParser {
public static void main(String[] args) {
int tokenIndex = 2;
CityParser parser = new CityParser();
for (String arg : args) {
System.out.println((String.format("line: '%s' tokenIndex: %d token: %s", args, tokenIndex, parser.getToken(arg, tokenIndex))));
}
}
public String getToken(String line, int tokenIndex) {
String token = null;
if ((line != null) && (line.trim().length() > 0)) {
String [] tokens = line.split("\\s+");
if ((tokens.length > 0)) {
token = tokens[tokenIndex];
}
}
return token;
}
}
You can search for the character " ". So for every line, count two " "'s then record kbd.next() to get the word.
I want to get the highest available string value in java how can i achieve this.
Example: hello jameswangfron
I want to get the highest string "jameswangfron"
String Text = request.getParameter("hello jameswangfron");
Please code example.
public class HelloWorld{
public static void main(String []args){
String text = "hello jameswangfron";
String[] textArray = text.split(" ");
String biggestString = "";
for(int i=0; i<textArray.length; i++){
if(i==0) {
textArray[i].length();
biggestString = textArray[i];
} else {
if(textArray[i].length()>textArray[i-1].length()){
biggestString = textArray[i];
}
}
}
System.out.println("Biggest String : "+biggestString);
}
}
And it shows the output as
Biggest String : jameswangfron
Maybe this will be easyer to understand
public class HelloWorld {
public static void main(String[] args) {
System.out.println(StringManipulator.getMaxLengthString("hello jameswangfron", " "));
}
}
class StringManipulator{
public static String getMaxLengthString(String data, String separator){
String[] stringArray = data.split(separator);
String toReturn = "";
int maxLengthSoFar = 0;
for (String string : stringArray) {
if(string.length()>maxLengthSoFar){
maxLengthSoFar = string.length();
toReturn = string;
}
}
return toReturn;
}
}
But there is a catch. If you pay attention to split method from class String, you will find out that the spliter is actually a regex. For your code, i see that you want to separate the words (which means blank space). if you want an entire text to search, you have to pass a regex.
Here's a tip. If you want your words to be separated by " ", ".", "," (you get the ideea) then you should replace the " " from getMaxLengthString method with the following
"[^a-zA-Z0-9]"
If you want digits to split up words, simply put
"[^a-zA-Z]"
This tells us that we use the separators as anything that is NOT a lower case letter or upper case letter. (the ^ character means you don't want the characters you listed in your brackets [])
Here is another way of doing this
"[^\\w]"
\w it actually means word characters. so if you negate this (with ^) you should be fine