Accessing an int[] inside an ArrayList - 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);
}

Related

Kotlin algorithm to reverse a given string

I'm creating an algorithm in Kotlin that should reverse a given string and output it, so, for example, the string would be "Hello World! and the output would be "olleH !dlroW. I know there's a function that does this already but I'm practising with loops and if statements so I'm doing it myself.
So far, I've got most of a working solution, the only problem with the code I have in that it only works with odd length strings, because of a while loop. I've put what I have in this post.
I'm stuck on what to change to make this program work with strings that are of an even length, currently with those strings, the program falls into an infinite loop because the condition is never met.
The exclusion part of the program will jump over characters that are included in the exclusion string, I've already tested this and it works fine, provided the string minus the skipped character is not of even length.
fun main() {
val userInput = ""
val exclusion = ""
val wordsInString = userInput.split(" ")
var wordsSize = wordsInString.size
var wordPointer = 0
while (wordPointer < wordsSize) {
var currentWord = wordsInString[wordPointer]
var charArray = currentWord.toCharArray()
var charPointerOne = 0
var charPointerTwo = currentWord.length - 1
while (charPointerOne != charPointerTwo) {
if (exclusion.contains(charArray[charPointerOne])) {
charPointerOne++
} else if (exclusion.contains(charArray[charPointerTwo])) {
charPointerTwo--
} else {
var charToSwtichOne = charArray[charPointerOne]
var charToSwitchTwo = charArray[charPointerTwo]
charArray[charPointerOne] = charToSwitchTwo
charArray[charPointerTwo] = charToSwtichOne
charPointerOne++
charPointerTwo--
}
}
wordPointer++
var outputString = String(charArray)
print(outputString + " ")
}
}
You need to change the loop control condition to use < instead of !=. because in case of even length strings they simply never meet and jump over. for example if you had a String of length two, then on first iteration charPointerOne will have value 0 and charPointerTwo will have value 1, and on the next iteration charPointerOne will be incremented to 1 and charPointerTwo will be decremented to 0 and these values still satisfy the loop control hence the loop continues. So to fix this change your code as
while (charPointerOne < charPointerTwo)

check is the value exists in array Google Sheets scripting?

I need to check if the certain value exists in both arrays and if exists remove this element from the second array. I know that it exists.
taking the 1st element from array doubleTue, taking the index where is this value in amTue and pmTue then remove those by using splice command.
But now my code is having problem on getting the first value.
tried as in level array: var val = doubleTue[i]
and 2 level array: var val - doubleTue[i][0]
tried toString(), read()
for (var n=0; n<doubleTue.length; n++)
{
var val = doubleTue[i][0];
var val1 = amTue.indexOf(val);
if (val1!=-1) {amTue.splice(val1, 1);};
var val2=pmTue.indexOf(val);
if (val2!=-1) {pmTue.splice(val2, 1); };
}
}
the issue is found. i have used wrong variable for looping. hehe. copy past issue
thnks all

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

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})

Make line chart with values and dates

In my app i use ios-charts library (swift alternative of MPAndroidChart).
All i need is to display line chart with dates and values.
Right now i use this function to display chart
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Items count")
let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
dateChartView.data = lineChartData
}
And this is my data:
xItems = ["27.05", "03.06", "17.07", "19.09", "20.09"] //String
let unitsSold = [25.0, 30.0, 45.0, 60.0, 20.0] //Double
But as you can see - xItems are dates in "dd.mm" format. As they are strings they have same paddings between each other. I want them to be more accurate with real dates. For example 19.09 and 20.09 should be very close. I know that i should match each day with some number in order to accomplish it. But i don't know what to do next - how i can adjust x labels margins?
UPDATE
After small research where i found out that many developers had asked about this feature but nothing happened - for my case i found very interesting alternative to this library in Swift - PNChart. It is easy to use, it solves my problem.
The easiest solution will be to loop through your data and add a ChartDataEntry with a value of 0 and a corresponding label for each missing date.
In response to the question in the comments here is a screenshot from one of my applications where I am filling in date gaps with 0 values:
In my case I wanted the 0 values rather than an averaged line from data point to data point as it clearly indicates there is no data on the days skipped (8/11 for instance).
From #Philipp Jahoda's comments it sounds like you could skip the 0 value entries and just index the data you have to the correct labels.
I modified the MPAndroidChart example program to skip a few data points and this is the result:
As #Philipp Jahoda mentioned in the comments the chart handles missing Entry by just connecting to the next data point. From the code below you can see that I am generating x values (labels) for the entire data set but skipping y values (data points) for index 11 - 29 which is what you want. The only thing remaining would be to handle the x labels as it sounds like you don't want 15, 20, and 25 in my example to show up.
ArrayList<String> xVals = new ArrayList<String>();
for (int i = 0; i < count; i++) {
xVals.add((i) + "");
}
ArrayList<Entry> yVals = new ArrayList<Entry>();
for (int i = 0; i < count; i++) {
if (i > 10 && i < 30) {
continue;
}
float mult = (range + 1);
float val = (float) (Math.random() * mult) + 3;// + (float)
// ((mult *
// 0.1) / 10);
yVals.add(new Entry(val, i));
}
What I did is fully feed the dates for x data even no y data for it, and just not add the data entry for the specific xIndex, then it will not draw the y value for the xIndex to achieve what you want, this is the easiest way since you just write a for loop and continue if you detect no y value there.
I don't suggest use 0 or nan, since if it is a line chart, it will connect the 0 data or bad things will happen for nan. You might want to break the lines, but again ios-charts does not support it yet (I also asked a feature for this), you need to write your own code to break the line, or you can live with connecting the 0 data or just connect to the next valid data.
The down side is it may has performance drop since many xIndex there, but I tried ~1000 and it is acceptable. I already asked for such feature a long time ago, but it took lot of time to think about it.
Here's a function I wrote based on Wingzero's answer (I pass NaNs for the entries in the values array that are empty) :
func populateLineChartView(lineChartView: LineChartView, labels: [String], values: [Float]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<labels.count {
if !values[i].isNaN {
let dataEntry = ChartDataEntry(value: Double(values[i]), xIndex: i)
dataEntries.append(dataEntry)
}
}
let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Label")
let lineChartData = LineChartData(xVals: labels, dataSet: lineChartDataSet)
lineChartView.data = lineChartData
}
The solution which worked for me is splitting Linedataset into 2 Linedatasets. First would hold yvals till empty space and second after emptyspace.
//create 2 LineDataSets. set1- till empty space set2 after empty space
set1 = new LineDataSet(yVals1, "DataSet 1");
set2= new LineDataSet(yVals2,"DataSet 1");
//load datasets into datasets array
ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
dataSets.add(set1);
dataSets.add(set2);
//create a data object with the datasets
LineData data = new LineData(xVals, dataSets);
// set data
mChart.setData(data);

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.