Get array of double from list of array of double, where first value in array is the max first value using linq - vb.net

I want to get the array of doubles from a list of an array of doubles where the first value of the array is the highest value as compared to the first value of the other arrays in the list
For example, if the list of arrays are (4,5) , (-3,2) , (7,1) then it would return (7,1).
I tried this but no success:
Dim vertices as List(of Double()) = MethodToGetList()
dim rv as Double() = vertices.Select(Function(x As Double()) x.First.MaxValue).ToArray

Sorry, my basic is a bit rusty, I'll do it in C#, I hope you'll get the gist.
Whenever you want a LINQ function, where you need to examine every item of your sequence exactly once, and you want to do something with the item that is currently being examined, think of Aggregate.
This will initialize variable highestValue with your first source element; then it will compare every source element with the highestValue and keep the one that is highest:
List<List<double>> mySource = ...
var result = mySource.Aggregate( (highestValue, nextValue) =>
(nextValue[0] > highestValue[0]) ? nextValue : highestValue);
This will be similar to:
List<double> highestValue = mySource[0];
for (int i=1; i<mySource.Count; ++i)
{
if (mySource[i][0] > higestValue[0])
{
// found a new highestValue
highestValue = mySource[i];
}
// else: keep the highest value
}
It is easy to see, that this only works if mySource is not empty. If you have an empty source, you should think of what you want as a result. We will initialize with this emptyResult:
List<double> emptyResult = ... // what do you want to use if there is nothing in your source?
List<double> highestValue = emptyResult;
for (int i=0; i<mySource.Count; ++i)
{
if (mySource[i][0] > higestValue[0])
{
// found a new highestValue
highestValue = mySource[i];
}
}
And now in LINQ: use the other Aggregate:
var result = mySource.Aggregate(emptyResult, // use this as seeder
(nextValue[0] > highestValue[0]) ? nextValue : highestValue);
This will help if you have an empty sequence. Buf what if one of your Lists in the source is null or empty?
Let's assume you don't want to consider them at all:
var nonEmptyArrays = mySource.Where(list => list != null && list.Count != 0)
var result = noneEmptyArrays.Aggregate((emptyResult, // use this as seeder
(nextValue[0] > highestValue[0]) ? nextValue : highestValue);
Simple comme bonjour!

Try this. This orders the vertices list of arrays by the first position of each array, then by the second position of the array. Then in the case of the same data (below), the list would look like: (7,1), (7,2), .... Then last piece of the statement grabs the first element in the sorted list so would return (7, 1)
Dim rv As Double() = vertices.OrderByDescending(Function(v) v(0)).ThenBy(Function(v) v(1)).FirstOrDefault
Data to test:
Dim vertices As List(Of Double()) = New List(Of Double())
vertices.Add(New Double() {4, 5})
vertices.Add(New Double() {-1, 2})
vertices.Add(New Double() {7, 1})
vertices.Add(New Double() {7, 2})

Related

convert listbox value to comma separated string with single quotes

i have a listbox with more than 100 items i want this 100 items to be comma separated with single quotes e.g: ''abc','def'' i want this to search in a select clause
List<string> SelectedValue = new List<string>();
foreach (ListItem lst in ListBox2.Items)
{
if (lst.Selected)
{
SelectedValue.Add(lst.Value);
}
}
string.Join(",",SelectedValue.Select(x=>string.Format("'{0}'",x)));
its giving me error 'the best overloaded method match for 'string.join has some invalid arguments, what an doing wrong here
Might I suggest a slightly different approach using a StringBuilder instead of putting the items into a List object? You are flatting these out to CSV anyways, so why not just build it that way like so..
var SB = new StringBuilder();
foreach (ListItem lst in ListBox2.Items)
{
if (lst.Selected)
{
SB.Append("'" + list.value + "',");
}
}
var FinalString = SB.ToString().Substring(0, (SB.Length - 1));
You linq query returns a result of type IEnumerable you must convert it to a string array:
List<string> selectedValue = (from ListItem lst in ListBox1.Items
where lst.Selected
select lst.Value).ToList();
//convert to array using ToArray()
string[] arr = selectedValue.Select(x => string.Format("'{0}'", x)).ToArray();
string data = string.Join(",",arr);
You need to convert the result of SelectedValue.Select to an array:
String result = string.Join(",", SelectedValue.Select(x => string.Format("'{0}'", x)).ToArray());`

String is to Substring, as ArrayList is to?

In Java, and many other languages, one can grab a subsection of a string by saying something like String.substring(begin, end). My question is, Does there exist a built-in capability to do the same with Lists in Java that returns a sublist from the original?
This method is called subList and exists for both array and linked lists. Beware that the list it returns is backed by the existing list so updating the original one will update the slice.
The answer can be found in the List API: List#subList(int, int) (can't figure out how to get the link working....)
Be warned, though, that this is a view of the underlying list, so if you change the original list, you'll change the sublist, and the semantics of the sublist is undefined if you structurally modify the original list. So I suppose it isn't strictly what you're looking for...
If you want a structurally independent subsection of the list, I believe you'll have to do something like:
ArrayList<something> copy = new ArrayList<>(oldList.subsection(begin, end));
However, this will retain references to the original objects in the sublist. You'll probably have to manually clone everything if you want a completely new list.
The method is called sublist and can be found here in the javadocs
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#subList(int, int)
You can use subList(start, end)
ArrayList<String> arrl = new ArrayList<String>();
//adding elements to the end
arrl.add("First");
arrl.add("Second");
arrl.add("Third");
arrl.add("Random");
arrl.add("Click");
System.out.println("Actual ArrayList:"+arrl);
List<String> list = arrl.subList(2, 4);
System.out.println("Sub List: "+list);
Ouput :
Actual ArrayList:[First, Second, Third, Random, Click]
Sub List: [Third, Random]
You might just want to make a new method if you want it to be exactly like substring is to String.
public static List<String> sub(List<String> strs, int start, int end) {
List<String> ret = new ArrayList<>(); //Make a new empty ArrayList with String values
for (int i = start; i < end; i++) { //From start inclusive to end exclusive
ret.add(strs.get(i)); //Append the value of strs at the current index to the end of ret
}
return ret;
}
public static List<String> sub(List<String> strs, int start) {
List<String> ret = new ArrayList<>(); //Make a new empty ArrayList with String values
for (int i = start; i < strs.size(); i++) { //From start inclusive to the end of strs
ret.add(strs.get(i)); //Append the value of strs at the current index to the end of ret
}
return ret;
}
If myStrings is an ArrayList of the following Strings: {"do","you","really","think","I","am","addicted","to","coding"}, then sub(myStrings,1,6) would return {"you", "really", "think", "I", "am"} and sub(myStrings,4) would return {"I", "am", "addicted", "to", "coding"}. Also by doing sub(myStrings, 0) it would rewrite myStrings as a new ArrayList which could help with referencing problems.

Accessing an int[] inside an ArrayList

I'm trying to make a program that reads points (e.g. (2,4), (0,0) ) from a file and tried using ArrayList since I don't know how many many points there will be. However only the last read point seems to get stored. I think only the pointer of nInput[] gets stored and not the actual value hence any subsequent sc.next() only seem to change the existing nInput[] in the ArrayList.
Ex input file:
-1 2
0 1
0 0 <<< I would get this as the only output
OR
-1 2
0 4
9 9 << This would be the only output
int nInput = new int[2];
ArrayList<int[]> aPoints = new ArrayList<int[]>();
while(sc.hasNext()){
nInput[0] = Integer.parseInt(sc.next());
nInput[1] = Integer.parseInt(sc.next());
aPoints.add(nInput);
}
for(int i<0; i<aPoints.size(); i++)
System.out.println(aPoints.get(i)[0]+" "+ aPoints.get(i)[1]);
How do I store int[] into an ArrayList?
Edit: First I gave pseudocode but I think you need Java code:
(I assume sc as a Scanner object)
ArrayList<int[]> list = new ArrayList<int[]>();
while(sc.hasNext) {
int[] array = new int[2];
array[0] = sc.nextInt();
array[1] = sc.nextInt();
list.add(array);
}

Get a value from array based on the value of others arrays (VB.Net)

Supposed that I have two arrays:
Dim RoomName() As String = {(RoomA), (RoomB), (RoomC), (RoomD), (RoomE)}
Dim RoomType() As Integer = {1, 2, 2, 2, 1}
I want to get a value from the "RoomName" array based on a criteria of "RoomType" array. For example, I want to get a "RoomName" with "RoomType = 2", so the algorithm should randomize the index of the array that the "RoomType" is "2", and get a single value range from index "1-3" only.
Is there any possible ways to solve the problem using array, or is there any better ways to do this? Thank you very much for your time :)
Note: Code examples below using C# but hopefully you can read the intent for vb.net
Well, a simpler way would be to have a structure/class that contained both name and type properties e.g.:
public class Room
{
public string Name { get; set; }
public int Type { get; set; }
public Room(string name, int type)
{
Name = name;
Type = type;
}
}
Then given a set of rooms you can find those of a given type using a simple linq expression:
var match = rooms.Where(r => r.Type == 2).Select(r => r.Name).ToList();
Then you can find a random entry from within the set of matching room names (see below)
However assuming you want to stick with the parallel arrays, one way is to find the matching index values from the type array, then find the matching names and then find one of the matching values using a random function.
var matchingTypeIndexes = new List<int>();
int matchingTypeIndex = -1;
do
{
matchingTypeIndex = Array.IndexOf(roomType, 2, matchingTypeIndex + 1);
if (matchingTypeIndex > -1)
{
matchingTypeIndexes.Add(matchingTypeIndex);
}
} while (matchingTypeIndex > -1);
List<string> matchingRoomNames = matchingTypeIndexes.Select(typeIndex => roomName[typeIndex]).ToList();
Then to find a random entry of those that match (from one of the lists generated above):
var posn = new Random().Next(matchingRoomNames.Count);
Console.WriteLine(matchingRoomNames[posn]);

ActionScript 2: How do I determine the number of keys in an associative array without iterating?

Is there a function that allows me to determine the number of keys in an ActionScript 2 associative array without iterating over that array?
// ascertain the length/size of an associative array
var o:Object = new Object();
o["k1"] = "v1";
o["k2"] = "v2";
o["k3"] = "v3";
I'd expect there to be an "o.size" or "o.length" that would return 3.
Thanks.
var o:Object = new Object();
o["k1"] = "v1";
o["k2"] = "v2";
o["k3"] = "v3";
var len:Number = 0;
for( i in o ) len++;
trace( len );
Sorry, there's no length/size for an Object, iteration is your only choice. AS3 has better options for this with the Dictionary class.