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)
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
Hi I was trying to solve the interleaving strings problem.Here is the detailed explanation of the problem. https://practice.geeksforgeeks.org/problems/interleaved-strings/1
I was trying using lcs but it was not passing leetcode cases. Here is my Code:-
(I am taking lcs from start and end)
class Solution {
public boolean isInterLeave(String a, String b, String c) {
StringBuffer s=new StringBuffer();
StringBuffer s1=new StringBuffer();
StringBuffer s2=new StringBuffer();
StringBuffer s4=new StringBuffer();
int m=a.length();
int n=c.length();
int q=b.length();
if(n!=m+q){
return false;
}
LinkedHashSet<Integer> res2= new LinkedHashSet<Integer>();
res2= lcs(a,c,m,n);
LinkedHashSet<Integer> res4= new LinkedHashSet<Integer>();
res4= lcs(b,c,q,n);
for(int i=0;i<n;i++){
if(res2.contains(i)==false){
s.append(c.charAt(i));
}
}
for(int i=0;i<n;i++){
if(res4.contains(i)==false){
s1.append(c.charAt(i));
}
}
LinkedHashSet<Integer> res5= new LinkedHashSet<Integer>();
res5= LCS(a,c,m,n);
for(int i=0;i<n;i++){
if(res5.contains(i)==false){
s2.append(c.charAt(i));
}
} LinkedHashSet<Integer> res6= new LinkedHashSet<Integer>();
res6= LCS(b,c,q,n);
for(int i=0;i<n;i++){
if(res6.contains(i)==false){
s4.append(c.charAt(i));
}
}
String z=s.toString();
String u=s1.toString();
String v=s2.toString();
String w=s4.toString();
if( (b.equals(z)==true || a.equals(u)==true) || ( b.equals(v)==true || a.equals(w)==true)){
return true;
}
else{
return false;
}
}
public static LinkedHashSet<Integer> lcs(String X, String Y, int m, int n)
{
int[][] L = new int[m+1][n+1];
// Following steps build L[m+1][n+1] in bottom up fashion. Note
// that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
// Following code is used to print LCS
// Create a character array to store the lcs string
LinkedHashSet<Integer> linkedset =
new LinkedHashSet<Integer>();
// Start from the right-most-bottom-most corner and
// one by one store characters in lcs[]
int i=1;
int j=1;
while (i <= m && j <= n)
{
// If current character in X[] and Y are same, then
// current character is part of LCS
if (X.charAt(i-1) == Y.charAt(j-1))
{
// Put current character in result
linkedset.add(j-1);
// reduce values of i, j and index
i++;
j++;
}
// If not same, then find the larger of two and
// go in the direction of larger value
else if (L[i-1][j] > L[i][j-1])
i++;
else
j++;
}
return linkedset;
}
public static LinkedHashSet<Integer> LCS(String X, String Y, int m, int n)
{
int[][] L = new int[m+1][n+1];
// Following steps build L[m+1][n+1] in bottom up fashion. Note
// that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
// Following code is used to print LCS
// Create a character array to store the lcs string
LinkedHashSet<Integer> linkedset =
new LinkedHashSet<Integer>();
// Start from the right-most-bottom-most corner and
// one by one store characters in lcs[]
int i = m;
int j = n;
while (i > 0 && j > 0)
{
// If current character in X[] and Y are same, then
// current character is part of LCS
if (X.charAt(i-1) == Y.charAt(j-1))
{
// Put current character in result
linkedset.add(j-1);
// reduce values of i, j and index
i--;
j--;
}
// If not same, then find the larger of two and
// go in the direction of larger value
else if (L[i-1][j] > L[i][j-1])
i--;
else
j--;
}
return linkedset;
}
}
Can anyone suggest an LCS approach to this problem?.My code is not passing the following test case
"cacabcbaccbbcbb" -String A
"acaaccaacbbbabbacc"-String B
"accacaabcbacaccacacbbbbcbabbbbacc"-String C
This will be the LCS+DP approach. Try it out:
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int m = s1.length(), n = s2.length();
if (n + m != s3.length()) return false;
if (s3.length() == 0) return true;
boolean[][] dp = new boolean[m+1][n+1];
dp[0][0] = true;
for (int i = 0; i <= m; i++) {
if (s1.substring(0, i).equals(s3.substring(0, i)))
dp[i][0] = true;
else
dp[i][0] = false;
}
for (int j = 0; j <= n; j++) {
if (s2.substring(0, j).equals(s3.substring(0, j)))
dp[0][j] = true;
else
dp[0][j] = false;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j] = (dp[i-1][j] && s1.charAt(i-1) == s3.charAt(i+j-1))
|| (dp[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1));
}
}
return dp[m][n];
}
}
I am new to Revit API and am working in C#. I want to get the schedule element parameters value using C#. I used the below code to get the view schedule.
var viewSchedule = new FilteredElementCollector(document)
.OfClass(typeof(ViewSchedule))
.FirstOrDefault(e => e.Name == "MyScheduleName") as ViewSchedule;
Schedule Element Data
From the above schedule, I used the below code to get the element data (please refer the above screenshot link) but it taking long time to reflect the output (10 to 15 seconds).
var rowCount = viewSchedule.GetTableData().GetSectionData(SectionType.Body).NumberOfRows;
var colCount = viewSchedule.GetTableData().GetSectionData(SectionType.Body).NumberOfColumns;
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < colCount; j++)
{
data += viewSchedule.GetCellText(SectionType.Body, i, j);
}
}
Please let me know is there any alternate approach to get the schedule data using C#.
Thanks in advance.
Maybe you can also use ViewSchedule.Export as demonstrated by The Building Coder discussing The Schedule API and Access to Schedule Data.
Yes, you can easily access Schedule data without exporting.
Firstly, get all the schedules and read the data cell by cell. Secondly, create dictionary and store data in form of key, value pairs. Now you can use the schedule data as you want. I have tried this in Revit 2019.
Here is the implementation.
public void getScheduleData(Document doc)
{
FilteredElementCollector collector = new FilteredElementCollector(doc);
IList<Element> collection = collector.OfClass(typeof(ViewSchedule)).ToElements();
String prompt = "ScheduleData :";
prompt += Environment.NewLine;
foreach (Element e in collection)
{
ViewSchedule viewSchedule = e as ViewSchedule;
TableData table = viewSchedule.GetTableData();
TableSectionData section = table.GetSectionData(SectionType.Body);
int nRows = section.NumberOfRows;
int nColumns = section.NumberOfColumns;
if (nRows > 1)
{
//valueData.Add(viewSchedule.Name);
List<List<string>> scheduleData = new List<List<string>>();
for (int i = 0; i < nRows; i++)
{
List<string> rowData = new List<string>();
for (int j = 0; j < nColumns; j++)
{
rowData.Add(viewSchedule.GetCellText(SectionType.Body, i, j));
}
scheduleData.Add(rowData);
}
List<string> columnData = scheduleData[0];
scheduleData.RemoveAt(0);
DataMapping(columnData, scheduleData);
}
}
}
public static void DataMapping(List<string> keyData, List<List<string>>valueData)
{
List<Dictionary<string, string>> items= new List<Dictionary<string, string>>();
string prompt = "Key/Value";
prompt += Environment.NewLine;
foreach (List<string> list in valueData)
{
for (int key=0, value =0 ; key< keyData.Count && value< list.Count; key++,value++)
{
Dictionary<string, string> newItem = new Dictionary<string, string>();
string k = keyData[key];
string v = list[value];
newItem.Add(k, v);
items.Add(newItem);
}
}
foreach (Dictionary<string, string> item in items)
{
foreach (KeyValuePair<string, string> kvp in item)
{
prompt += "Key: " + kvp.Key + ",Value: " + kvp.Value;
prompt += Environment.NewLine;
}
}
Autodesk.Revit.UI.TaskDialog.Show("Revit", prompt);
}
I've been trying to create a program where it takes an array input through an object and passes the parameter (simulation of ArrayList).
I keep getting the java.lang.ArrayIndexOutOfBoundsException in which I'm guessing I'm not accessing the array properly..
What can I do to enhance the test object and/ or the constructor?
public class MyArrayList{
public int[] x;
public MyArrayList( ){
x = new int[0];
}
public MyArrayList(int[] k)
{
for (int i = 0; i < x.length; i++)
x[i] = k[i];
k = x;
}
public void add(int index).......
public int size().....
public int get(int index).....
public void set(int index, int value).......
public String toString( )........
Below is the class I am having trouble with.
public class TestMyArrayList
{
public static void main(String[] args)
{
MyArrayList test = new MyArrayList();
test.x[0] = 1;
test.x[1] = 2;
test.x[2] = 3;
test.x[3] = 4;
test.x[4] = 5;
test.add(2);
test.set(1,3);
int a, b;
String c;
a = test.size( );
b = test.get(5);
c = test.toString( );
System.out.println("The size of the array is" + a);
System.out.println("The value at that position is " + b);
System.out.println("The resulting string is: " + c);
}
}
This line from your constructor is the only location (in the code you've shown) where the array x is initialized:
x = new int[0];
And it creates a zero length array. Assuming you are not reinitializing the array somewhere else then all these lines will definitely fail:
test.x[0] = 1;
test.x[1] = 2;
test.x[2] = 3;
test.x[3] = 4;
test.x[4] = 5;
Because your array length is zero. So:
Initialize your array to a more sensible value
Consider encapsulating the array so that callers cannot directly access it. This will make it much easier to code up your application in the long run
Side note (aka bonus):
This other constructor of yours:
public MyArrayList(int[] k) {
for (int i = 0; i < x.length; i++)
x[i] = k[i];
k = x;
}
has some issues as well:
You should reinitialize your array x to be the same size as the supplied array, prior to copying over the values.
The assignment k = x is basically a no-op, because it doesn't actually change what k was pointing to outside of the method.
Overall, it should look more like this:
public MyArrayList(int[] k) {
super();
if(k != null) {
x = new int[k.length];
for (int i = 0; i < x.length; i++) {
x[i] = k[i];
}
} else {
x = null;
}
}
I want to create a String from an ArrayList. Currently, I am only able to return the last value from the ArrayList. My code:
eachstep = new ArrayList<String>();
for (int i = 0; i < parsedsteps.size(); i++) {
eachstep.add(parsedsteps.get(i).replaceAll("<[^>]*>", ""));
}
for (int i = 0; i < eachstep.size(); i++) {
String directions = i + "."+" "+eachstep.get(i)+"\n"+;
}
Gives me:
3. This is step 3.
Instead of:
1. This is step 1.
2. This is step 2.
3. This is step 3.
How do I make my for loop create a String with all the values from the ArrayList?
You'll need to declare your string outside of the loop, and I suggest using StringBuilder as well, it's more efficient for building strings like this.
StringBuilder directions = new StringBuilder();
for( int i = 0; i < eachstep.size(); i++ )
{
directions.append( i + "." + " " + eachstep.get( i ) + "\n" );
}
Then when you want to get the string out of the StringBuilder, just call directions.toString().
try this
eachstep = new ArrayList<String>();
for (int i = 0; i < parsedsteps.size(); i++) {
eachstep.add(parsedsteps.get(i).replaceAll("<[^>]*>", ""));
}
String directions="";
for (int i = 0; i < eachstep.size(); i++) {
directions += i + "."+" "+eachstep.get(i)+"\n"+;
}
If you have large size of string array, you might want to consider using StringBuilder, e.g
StringBuilder builder = new StringBuilder();
for(String str: eachstep ){
builder.append(i).append(".").append(str).append("\n");
}
String direction = builder.toString();
String directions = "";
for (int i = 0; i < eachstep.size(); i++) {
directions += i + "."+" "+eachstep.get(i)+"\n";
}