I want to sort records based on their integer value in descending order:
Example:
name1, 4
name2, 6
name3, 3
name4, 5
Should be re - arranged to this:
name2, 6
name4, 5
name1, 4
name3, 3
I've tried using the Array.Sort but I could not get it working.
As always I appreciate all of your help.
You can split the data into two arrays and use use array.sort to sort based on the integers.
Dim a() As String = {"name1", "name2", "name3", "name4"}
Dim ia() As Integer = {4, 6, 3, 5}
Array.Sort(ia, a)
This will sort both arrays in ascending order of ia. Iterate the arrays backward to get descending order.
Sub Main()
Dim StartArray(3) As Integer
'First let's assign the array elements before it is sorted
StartArray(0) = 4
StartArray(1) = 6
StartArray(2) = 3
StartArray(3) = 5
Array.Sort(StartArray) 'This sorts the array
For i As Integer = 0 To 3
Console.WriteLine(StartArray(i)) 'Prints the array elements to console
Next
Console.ReadLine()
End Sub
dim nos() as integer={1,2,3,4}
dim names() as string = {"a","b","c","d"}
for i = 0 to 3
array.sort(names &" "&nos)
next
console.readKey
Related
Hey everyone: I'm trying to make a function that digs through an array and adds values from range2 when the corresponding value from range1 equals criteria1.
I'm relatively new to VBA, so it's not the most elegant function in the world, but here's my code:
Function SingleArray(range1 As Range, range2 As Range, criteria1 As String)
Dim newrange() As Double
Dim d As Integer
Dim g As Integer
Dim i As Integer
g = Application.WorksheetFunction.CountIf(range1, criteria1)
ReDim newrange(g)
d = 1
For i = 0 To (range1.Count)
If range1(i) = criteria1 Then
newrange(d) = range2.Item(i).Value
d = d + 1
End If
Next i
SingleArray = newrange
End Function
Here is my data sample:
range2 range1
-5000 Bob
-5000 Jim
200 Bob
500 Jim
5000 Bob
200 Bob
300 Bob
1000 Bob
When I set the criteria as "Bob," the array that is returned is as follows:
{0,-5000,200,5000,200,300,1000}
I'm genuinely at a loss for how that zero is making it in there. Any thoughts you can provide would be most welcome!
1-D arrays default to a zero-based index structure (e.g. 0, 1, 2, 3, ....). You are looping through the ranges with a one based index (e.g. 1, 2, 3, 4, ...).
When you declare ReDim newrange(5) you are actually creating an array with six elements, not five (e.g. 0, 1, 2, 3, 4, 5)
You can make all arrays on that code sheet default to a one based index by putting this compiler directive at the top of the code sheet.
Option Base 1
You can also change the way the array is declared on the fly by specifying the Lower Boundary and the Upper Boundary.
ReDim newrange(1 to g)
I am new to Scala and this is the first time I'm using it. I want to read in a textfile with with two columns of numbers and store each column items in a separate list or array that will have to be cast as integer. For example the textfile looks like this:
1 2
2 3
3 4
4 5
1 6
6 7
7 8
8 9
6 10
I want to separate the two columns so that each column is stored in its on list or array.
Lets say you named the file as "columns", this would be a solution:
val lines = Source.fromFile("columns").getLines()
/* gets an Iterator[String] which interfaces a collection of all the lines in the file*/
val linesAsArraysOfInts = lines.map(line => line.split(" ").map(_.toInt))
/* Here you transform (map) any line to arrays of Int, so you will get as a result an Interator[Array[Int]] */
val pair: (List[Int], List[Int]) = linesAsArraysOfInts.foldLeft((List[Int](), List[Int]()))((acc, cur) => (cur(0) :: acc._1, cur(1) :: acc._2))
/* The foldLeft method on iterators, allows you to propagate an operation from left to right on the Iterator starting from an initial value and changing this value over the propagation process. In this case you start with two empty Lists stored as Tuple an on each step you prepend the first element of the array to the first List, and the second element to the second List. At the end you will have to Lists with the columns in reverse order*/
val leftList: List[Int] = pair._1.reverse
val rightList: List[Int] = pair._2.reverse
//finally you apply reverse to the lists and it's done :)
Here is one possible way of doing this:
val file: String = ??? // path to .txt in String format
val source = Source.fromFile(file)
scala> val columnsTogether = source.getLines.map { line =>
val nums = line.split(" ") // creating an array of just the 'numbers'
(nums.head, nums.last) // assumes every line has TWO numbers only
}.toList
columnsTogether: List[(String, String)] = List((1,2), (2,3), (3,4), (4,5), (1,6), (6,7), (7,8), (8,9), (6,10))
scala> columnsTogether.map(_._1.toInt)
res0: List[Int] = List(1, 2, 3, 4, 1, 6, 7, 8, 6)
scala> columnsTogether.map(_._2.toInt)
res1: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10)
I am studying VB.NET and I want to know better idea to get Keys by sorted values in Hashtable
Here is my solution that I built
Dim int_Value As Integer() = New Integer() {-9, 2, 8, 6, 8, 1, -9}
Dim int_Key As Integer() = New Integer() {1, 2, 3, 4, 5, 6, 7}
Dim Dum_Int(int_Key.Length) As Integer
Dim STORE_KEYS As New ArrayList
Array.Copy(int_Value, Dum_Int, Dum_Int.Length - 1)
Array.Sort(Dum_Int)
Array.Reverse(Dum_Int)
For I = 0 To Dum_Int.Length - 1
For II = 0 To int_Value.Length - 1
If Dum_Int(I) = int_Value(II) Then
STORE_KEYS.Add(int_Key(II))
int_Value(II) = Integer.MaxValue
End If
Next
Next
I got output like..
'' OUTPUT''
(0) 3 {Integer} Object
(1) 5 {Integer} Object
(2) 4 {Integer} Object
(3) 2 {Integer} Object
(4) 6 {Integer} Object
(5) 1 {Integer} Object
(6) 7 {Integer} Object
I assume that I have Hashtable.
I create two arrays and store both Keys (int_Key) and Values(Int_Value) From Hashtable
then I copy Value(Int_Value) array to Dum_Int to sort values
Whenever I found matching int value between Sorted Array and Original Value Array
I stored in to STORE_KEYS(arraylist) and I insert Max Int value to original array to prevent overlapping issue.
However, is there any way to improve this method ?
I don't believe that better sorting algor can't help to simplify this method.
Can you provide any hints to simplify this method?
thanks
The Array.Sort method has an overload that will sort an array based on another array:
Dim keys = myHastable.Keys.Cast(Of Integer)().ToArray()
Dim values = myHastable.Values.Cast(Of Integer)().ToArray()
Array.Sort(values, keys)
I have split the 1d array and i need convert it into a 2d array. The array consists of numbers (scores) and names as results of a numerical test.
Dim results1 As String = File.ReadAllText("Z:\scores class 1.txt")
Dim array = Split(results1, " ")
For i As Integer = 0 To array.Length - 1
Console.WriteLine(array(i))
Next
Console.WriteLine("Would you like these to be sorted? Press 1 for yes, 2 for no")
If Console.ReadLine = 1 Then
' do some stuff
ElseIf Console.ReadLine = 2 Then
' do some stuff
End If
Console.ReadLine()
That is my current code, what do i need to add?
Thanks for any help.
Converting 1D to 2D is possible when you have contigious key/value present to make it as index of array but in your case it is neither. So better option will be to use HashMap/HashTable in general. As per your requirement instead of using 2D array to represent name: value pair you should use a HashMap .
As per your statement in commnets you have an 1D array which holds name:value
i.e
String arr [] = { "jack", "23", "mat","45", "mike","56" }
You can better represent it as a HashMap .
HashMap<String,Integer> hm = new HashMap<String,Integer>();
hm.add("jack",23); // it will add score of 23 to name jack i.e "jack" : 23
hm.add("mat",45);
hm.add("mike",56);
Now you can easily manipulate any name:value pair
e.g. To get marks scored by "mat" just write hm.get("mat")
It will output the marks associated with mat i.e 45.
Dim array2((array.Length / 2) - 1, 1) As String
For i As Integer = 0 To (array.Length - 1) / 2 Step 1
array2(i, 0) = array(i * 2)
array2(i, 1) = array((i + 1) * 2 - 1)
Next
This creates a two dimensional array with the values from the 1d array.
I have a couple of college assignments I am having trouble with. Really I am just confused about one thing regarding an array. I need to declare a three column, 5 row array. The first two columns are integers and the third column is the letter grade. So I am very confused about declaring the data type since they are different. This is my first go-around with arrays, so please excuse my ignorance. Here is an what my array is supposed to look like.
Column 1 {0,300,350,400,450}
Column 2 {299,349,399,449,500}
Column 3 {F,D,C,B,A}
(It's a grading app)
I can solve the rest of the problem myself, I am just confused about this array portion. So my question is strictly about how to declare such an array. It say's to use a two-dimensional array which only confuses me more since there are three columns. Thank you!
2-dimensional array is correct. First index is column, second index is row.
Dim strData(,) As String 'Use String variable type, even for the numbers
Dim intRowCount As Integer = 5
Dim intColumnCount As Integer = 3
ReDim strData(intColumnCount - 1, intRowCount - 1) 'subtract 1 because array indices are 0-based. Column 0 = Range start, Column 1 = Range End, Column 2 = Grade
'first row
strData(0, 0) = "0" 'Range start
strData(1, 0) = "299" 'Range end
strData(2, 0) = "F" 'Grade
'second row
strData(0, 1) = "300"
strData(1, 1) = "349"
strData(2, 1) = "D"
'third row
strData(0, 2) = "350"
strData(1, 2) = "399"
strData(2, 2) = "C"
'fourth row
strData(0, 3) = "400"
strData(1, 3) = "449"
strData(2, 3) = "B"
'fifth row
strData(0, 4) = "450"
strData(1, 4) = "500"
strData(2, 4) = "A"
'Add a row
intRowCount = intRowCount + 1
ReDim Preserve strData(intColumnCount - 1, intRowCount - 1)
'sixth row
strData(0, 5) = "501"
strData(1, 5) = "600"
strData(2, 5) = "A+"
Note that Redim Preserve can only change the last index in the array, which is why we store in (column, row) order rather than the more traditional (row, column) order.
There are a couple of ways to approach this. One is to declare the array as Object type, and they assign integers or strings to the appropriate element. Some don't consider this socially acceptable, though, because it can lead to code that's difficult to debug.
You could also use a String type for a two dimensional array and save the integers in string variables. This is also not normally done because of the conversion necessary for numeric comparisons and computation.
Another approach is to use a structure or class that contains the three values, and make an array of that.
For example,
Structure Item
Dim col1 as integer
Dim col2 as integer
Dim col3 as string
End Structure
Dim itemList(20) as Item
itemList(4).col1 = 23
itemList(4).col2 = 45
itemList(4).col3 = "somestring"