When dealing with a string of numbers let's say '12345', I would do something like this
String number = '12345';
List<String> listnumber = number.split("");
List<int> output = [];
for (int i = 0; i < listnumber.length; i++) {
if (i != listnumber.length - 1) {
output.add(int.parse(listnumber[i]));
}
List<String> temp = [listnumber[i]];
for (int j = i + 1; j < listnumber.length; j++) {
temp.add(listnumber[j]);
output.add(int.parse(temp.join()));
}
}
print(output.toString());
result:
[1, 12, 123, 1234, 12345, 2, 23, 234, 2345, 3, 34, 345, 4, 45]
Perfect! that's exactly what I want. But now I can't get the same result for a string of letters.
Can someone help me achieve the same result with a string such as 'abcde'.
Thanks in advance
void main(){
String number = 'abcde';
List<String> listnumber = number.split("");
List<String> output = []; // int -> String
for (int i = 0; i < listnumber.length; i++) {
if (i != listnumber.length - 1 ) {
output.add(listnumber[i]); //
}
List<String> temp = [listnumber[i]];
for (int j = i + 1; j < listnumber.length; j++) {
temp.add(listnumber[j]); //
output.add((temp.join()));
}
}
print(output.toString());
}
Output:
[a, ab, abc, abcd, abcde, b, bc, bcd, bcde, c, cd, cde, d, de]
Related
CODE
void main() {
List<String> str = ["hello", "world"];
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str[i].length; j++) {
if (str[i][j] == 'o') {
str[i][j]='e';
print('$i,$j');
}
}
}
print(str);
}
The Error I get
The operator '[]=' isn't defined for the class 'String'.
Try correcting the operator to an existing operator, or defining a '[]=' operator.
str[i][j]='e';
If i comment this line //str[i][j]='e'; i get the location of the characters but i am unable to edit the string like we usually do in C++
String in Dart does not have a []= operator which means you cannot set a value on the String using the [] operator like you are trying to do.
This makes sense since String is immutable in Dart and calling the []= does not allow us to return anything, so we would not be able to get the modified String back.
We can instead call .replaceRange() on the String which allow us to replace a part of a String with some other String value. The method will return a new String with the change (since we are not allowed to change any existing String object).
With this, we can rewrite your example to:
void main() {
List<String> str = ["hello", "world"];
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str[i].length; j++) {
if (str[i][j] == 'o') {
str[i] = str[i].replaceRange(j, j + 1, 'e');
print('$i,$j');
}
}
}
print(str);
}
Which will output:
0,4
1,1
[helle, werld]
If the purpose is to replace all o with e, a more efficient solution would be to use the replaceAll() method:
void main() {
List<String> str = ["hello", "world"];
for (int i = 0; i < str.length; i++) {
str[i] = str[i].replaceAll('o', 'e');
}
print(str); // [helle, werld]
}
Simple way: Map and replaceAll
List<String> str = ["hello","world"];
str = str.map((s)=>
s.replaceAll("o", "e")
).toList();
print(str);
Result
Assuming "A B C D" to be a sentence, is there any dedicated name for two following string deconstructions :
1)
size:3 <=> {"ABC", "BCD"}
size:2 <=> {"AB","BC", "CD"}
2)
size:3 <=> {"ABC", "ABD", "BCD"}
size:2 <=> {"AB","AC", "AD", "BC", "BD", "CD"}
Please, note that we never permute elements...
Thank you in advance,
-Bast
Like java code
String sequence = "A B C D";
public List createConventions(String sequence,int mode) {
List<String> result = new ArrayList<>();
String[] elements = sequence.split(" ");
for (int i = 0; i < elements.length; i++) {
for (int j = i + 1; j < elements.length; j++) {
if (mode == 1) {
result.add(elements[i] + elements[j]);
} else if (mode == 2) {
for (int k = j + 1; k < elements.length; k++) {
result.add(elements[i] + elements[j] + elements[k]);
}
}
}
}
return result;
}
I have two matrices {1,2,3;4,5,6;7,8,9} and {1,4;2,5;3,6}.
The following code is a matrix multiplication in apache spark. But it is giving me wrong output as {15.0,29.0;36.0,71.0;57.0,113.0}. I want to know where I am done mistake?
JavaRDD<String> lines = ctx
.textFile(
"/home/hduser/Desktop/interpolation/Kriging/MatrixMultiplication/MatrixA.csv")
.cache();
JavaRDD<String> lines1 = ctx
.textFile(
"/home/hduser/Desktop/interpolation/Kriging/MatrixMultiplication/MatrixB.csv")
.cache();
JavaRDD<Vector> rows = lines.map(new Function<String, Vector>() {
#Override
public Vector call(String line) throws Exception {
String[] lineSplit = line.split(",");
double[] arr = new double[lineSplit.length];
for (int i = 0; i < lineSplit.length; i++) {
arr[i] = Double.parseDouble(lineSplit[i]);
}
Vector dv = Vectors.dense(arr);
return dv;
}
});
//rows.saveAsTextFile("/home/hduser/Desktop/interpolation/Kriging/MatrixMultiplication/MatrixA_output");
RowMatrix A = new RowMatrix(rows.rdd());
JavaRDD<Vector> rows1 = lines1.map(new Function<String, Vector>() {
#Override
public Vector call(String line) throws Exception {
String[] lineSplit = line.split(",");
double[] arr = new double[lineSplit.length];
for (int i = 0; i < lineSplit.length; i++) {
arr[i] = Double.parseDouble(lineSplit[i]);
}
Vector dv = Vectors.dense(arr);
return dv;
}
});
List<Vector> arrList = new ArrayList<Vector>();
arrList = rows1.toArray();
double[] arr1 = new double[(int) rows1.count() * arrList.get(0).size()];
int k=0;
for (int i = 0; i < arrList.size(); i++) {
for (int j = 0; j < arrList.get(i).size(); j++) {
arr1[k] = arrList.get(i).apply(j);
//System.out.println(arr1[k]);
k++;
}
}
Matrix B = Matrices.dense((int) rows1.count(), arrList.get(0)
.size(), arr1);
RowMatrix C = A.multiply(B);
RDD<Vector> rows2 = C.rows();
rows2.saveAsTextFile("/home/hduser/Desktop/interpolation/Kriging/MatrixMultiplication/Result");
Thanks in advance...
Matrices.dense constructs a column-major matrix (API doc), and you are traversing the array of rows in the wrong order.
I cannot look into your CSV files, but I guess you have a typo there as well. Why?
B has to be [1 3; 4 5; 2 6] in order to produce the wrong output, therefore the array has to be {1,4,2,3,5,6}, so MatrixB.csv probably contains:
1,4
2,3
5,6
(3 and 5 are switched)
I need to find the rank/index of a lottery combination and be able to reverse the process (Find the lottery combination given its rank).
Consider a lottery game with 5 balls from 1 to 45 and 1 powerball from 1 to 20. Duplication is not allowed and the order does not matter. The number of combinations is:
(45 * 44 * 43 * 42 * 41 / 5!) * 20 = 24,435,180
The first combination (index 0) is:
1, 2, 3, 4, 5, 1
The last combination (index 24,435,179) is:
41, 42, 43, 44, 45, 20
How can I convert a combination into its index and vice versa without exhaustively enumerating all combinations?
I came across this MSDN article, which shows how to get the combination of a given index. However, I don't know how to get the index from a combination. I've tried:
Choose(c1,k) + Choose(c2,k-1) + Choose(c3,k-2) + Choose(c4,k-3) ...
Where ci is the number at position i in the ordered combination set and k is the size of the set. Since the index of a combination depends on the range of the elements, this does not work. Additionally, I'm not sure if it is going to work with elements of different sizes in the set (e.g. main pool's range is 1-45, powerball's range is 1-20)
I was able to figure it out. I created a new Combination class, based on the MSDN example, which can convert a combination to an index and vice versa. A separate index is retrieved for each pool of numbers. All the indices are then combined to represent a combination with elements of different sizes.
A Pool class was also created to represent the settings of a pool (Range of elements, size etc). The Pool class:
public class Pool {
public int From { get; set; }
public int To { get; set; }
public int Size { get; set; }
public int Numbers { get { return (To - From + 1); } }
public Pool(int From, int To, int Size) {
this.From = From;
this.To = To;
this.Size = Size ;
}
}
The Combination class:
class Combination {
public Pool[] Pools { get; set; }
public long[][] Data { get; set; } //First index represents pool index, second represents the numbers
public Combination(Pool[] Pools, long[][] Data) {
this.Pools = Pools;
this.Data = Data;
if (Data.GetLength(0) != Pools.Length) {
throw (new ArgumentException("Invalid data length"));
}
for (int i = 0; i < Data.GetLength(0); i++) {
if (Data[i].Length != Pools[i].Size) {
throw (new ArgumentException("Invalid data length"));
}
}
}
public static Combination FromIndex(long Index, Pool[] Pools) {
long[][] elements = new long[Pools.Length][];
long[] c = new long[Pools.Length - 1];
long cumulative = 1;
for (int i = 0; i < Pools.Length - 1; i++) {
c[i] = Combination.Choose(Pools[i].Numbers, Pools[i].Size);
checked {
cumulative *= c[i];
}
}
for (int i = Pools.Length - 1; i >= 1; i--) {
long ind = Index / cumulative;
Index -= ind * cumulative;
cumulative /= c[i - 1];
elements[i] = Combination.FromIndex(ind, Pools[i]);
}
elements[0] = Combination.FromIndex(Index, Pools[0]);
return (new Combination(Pools, elements));
}
public static long[] FromIndex(long Index, Pool Pool) {
long[] ans = new long[Pool.Size];
long a = (long)Pool.Numbers;
long b = (long)Pool.Size;
long x = GetDual((long)Pool.Numbers, (long)Pool.Size, Index);
for (int k = 0; k < Pool.Size; k++) {
ans[k] = LargestV(a, b, x);
x -= Choose(ans[k], b);
a = ans[k];
b--;
}
for (int k = 0; k < Pool.Size; k++) {
ans[k] = ((long)Pool.Numbers - 1) - ans[k];
}
//Transform to relative
for (int i = 0; i < ans.Length; i++) {
ans[i] += Pool.From;
}
return (ans);
}
private static long GetDual(long To, long Size, long m) {
return (Choose(To, Size) - 1) - m;
}
public static long Choose(long To, long Size) {
if (To < 0 || Size < 0)
throw new Exception("Invalid negative parameter in Choose()");
if (To < Size)
return 0; // special case
if (To == Size)
return 1;
long delta, iMax;
if (Size < To - Size) {
delta = To - Size;
iMax = Size;
} else {
delta = Size;
iMax = To - Size;
}
long ans = delta + 1;
for (long i = 2; i <= iMax; ++i) {
checked {
ans = (ans * (delta + i)) / i;
}
}
return ans;
}
private static long LargestV(long a, long b, long x) {
long v = a - 1;
while (Choose(v, b) > x)
--v;
return v;
}
public long ToIndex() {
long Index = 0;
long cumulative = 1;
for (int i = 0; i < Pools.Length; i++) {
checked {
Index += ToIndex(i) * cumulative;
cumulative *= Combination.Choose(Pools[i].Numbers, Pools[i].Size);
}
}
return (Index);
}
public long ToIndex(int PoolIndex) {
long ind = 0;
for (int i = 0; i < Pools[PoolIndex].Size; i++) {
long d = (Pools[PoolIndex].Numbers - 1) - (Data[PoolIndex][i] - Pools[PoolIndex].From);
ind += Choose(d, Pools[PoolIndex].Size - i);
}
ind = GetDual(Pools[PoolIndex].Numbers, Pools[PoolIndex].Size, ind);
return (ind);
}
public override string ToString() {
string s = "{ ";
for (int i = 0; i < Data.Length; ++i) {
for (int k = 0; k < Data[i].Length; k++) {
s += Data[i][k] + " ";
}
if (i != Data.Length - 1) {
s += "| ";
}
}
s += "}";
return s;
}
}
To see this in action:
//Create pools
Pool[] pools = new Pool[2];
pools[0] = new Pool(1, 45, 5);
pools[1] = new Pool(1, 20, 1);
//Create a combination
long[][] data = new long[][] { new long[] { 41, 42, 43, 44, 45 }, new long[] { 20 } };
Combination combination = new Combination(pools, data);
//Get index from combination:
long index = combination.ToIndex();
Console.WriteLine("Index: " + index);
//Get combination from index:
Combination combFromIndex = Combination.FromIndex(index, pools);
Console.WriteLine("Combination: " + combFromIndex);
Output:
Index: 24435179
Combination: { 41 42 43 44 45 | 20 }
Hi any Body give me an idea how to convert a number to word.
For exm:- if number is 100 the word must be one hundred.
if number is 250 then word will be two hundred fifty etc.
If i give any input of a number then the corresponding word of out will be print in console.
Thanks
jay
-(NSString*)numberToWord:(NSInteger)number {
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
return [formatter stringFromNumber:[NSNumber numberWithInteger:number]];
}
I've made a Java program that converts any Integer type number (byte, short, int and even long !) into words.
This value goes into pentillions
One pentillion = 1000000 trillion
both in negative and positive, including zero.
Here you go :
package Practice.Program;
public class Num2Words {
private static long number;
private static String words = new String("");
public Num2Words(long n){ number = n; }
static String[] tp = {"", "thousand ", "million ", "billion ", "trillion ", "quadrillion ", "pentillion "};
static String[] od = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
static String[] td = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
static String[] tn = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
public String toWords(){
words = Long.toString(number);
int l = words.length();
boolean n = false;
if (number < 0){ n = true; number *= -1; --l;}
breaker : for (byte LOL = 0; LOL < 1; LOL++){
if (StringHasChar(words, '.')){ words = "Decimals not supported."; break breaker;}
if (l>19){ words = "too big"; break breaker;}
if (l==1) words = oneDigit(number); // one digit
else if (l==2) words = twoDigits(number); // two digits
else if (l==3) words = threeDigits(number); // three digits
else words = nDigits(number); // multiple digits
}
if (n == true) {words = "Minus "+words; number *= -1;}
return words;
}
private static String oneDigit(long n){
char[] ns = Long.toString(n).toCharArray();
return od[(char2num(ns[0]))];
}
private static String twoDigits(long n){
String s = "";
char[] ns = Long.toString(n).toCharArray();
if (n < 20){
s = td[(char2num(ns[1]))];
} else if (n < 100){
s = tn[char2num(ns[0])];
if (char2num(ns[1])!=0){ s += " " + od[char2num(ns[1])]; }
}
return s;
}
private static String threeDigits(long n){
String s = "", is = Long.toString(n);
long[] ns = String2longArray(is);
s = od[(int)(ns[0])] + " hundred";
if (ns[1]!=0&&ns[2]!=0){
long i = (ns[1])*10+(ns[2]);
s += " " + twoDigits(i);
} else {
if (ns[1]!=0) s += " " + twoDigits((ns[1]*10));
if (ns[2]!=0) s += " " + oneDigit(ns[2]);
}
return s;
}
private static String nDigits(long n){
String s = threeDigits(n);
int tpi = ((digits(n)+2)/3)-1, rtpi = 0;
long[] tfr = threeFromRight(n);
s = "";
for (; tpi >= 0; tpi--, rtpi++){
s = new Num2Words(tfr[tpi]).toWords() + " " + tp[rtpi] + s;
}
return s;
}
private static int digits(long n){
long ans = 0;
for (; n>0; n/=10, ans++);
return (int)(ans);
}
private static long[] threeFromRight(long n){
int tpi = (digits(n)+2)/3, nl = digits(n);
long[] ans=new long[tpi], ia=String2longArray(Long.toString(n)), ta=new long[3];
for (int i=nl, t=2, c=0, l=tpi*3; l >= 0; l--, c++, i--, t--){
try {ta[t] = ia[i-1];}
catch (ArrayIndexOutOfBoundsException e){ta[t]=0;}
if (((c+1)%3)==0){
--tpi;
ans[tpi] = longArrays2long(ta);
t = 3;
c = -1;
}
}
return ans;
}
private static int char2num(char c){
char[] ca = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
byte ia[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, ans = -1;
for (byte i = 0; i < 10; i++){ if (c == ca[i]){ ans = ia[i]; break;} }
return ans;
}
private static long[] String2longArray(String s){
char[] ca = s.toCharArray();
byte l = (byte)s.length();
long[] ans = new long[l];
for (byte i = 0; i < l; i++){ ans[i] = char2num(ca[i]); }
return ans;
}
private static long longArrays2long(long[] ia){
long ans = 0;
try { for (int i = 0; i >= 0; ans += ia[i], ans *= 10, ++i); }
catch (ArrayIndexOutOfBoundsException e){}
ans/=10;
return ans;
}
private static boolean StringHasChar(String s, char c){
char[] sca = s.toCharArray();
byte l = (byte)(s.length());
boolean ans = false;
for (byte i = 0; i > l; i++){
if (sca[i] == c) ans = true;
}
return ans;
}
public static void main(String[] args){
long n = -1053664648543756767l;
String words = new Num2Words(n).toWords();
System.out.println(n + " : " + words);
}
}
Note : The main(String[] args) is only for testing purposes. You may, or may not include it in your code.