Returning from a loop in groovy - arrays

i'm trying to get all of the array selected to be returned but
return breaks the loop, not allowed to use println etc, Its an array inside of an array called from a website, it only prints the first element then the loop breaks. Any help appreciated
def String citylist(String[][]data){
String result = null;
for(int i = 0; i < data.length; i++){
result = data[i][0];
return result;
}
}

I'm going to guess you want the first element of every array... it's hard to tell from the question...
If that's the case, you can do:
List<String> citylist(String[][]data){
data.collect { it[0] }
}

To get the first element of every array, this is what you need to do:
String[] citylist(String[][] data) {
String[] result = new String[data.length]
for (int i = 0; i < data.length; i++) {
result[i] = data[i][0]
}
return result
}
I was not sure wether your method signature is correct or not, so I changed it to return an array of String. But if you want a String you can do:
String citylist(String[][] data) {
String[] result = new String[data.length]
for (int i = 0; i < data.length; i++) {
result[i] = data[i][0]
}
return result.toString()
}
Same think if you can use a List:
def citylist(String[][] data) {
def result = []
for (int i = 0; i < data.length; i++) {
result << data[i][0]
}
return result
}
And then you can even use some nice Groovy features:
def citylist(String[][] data) {
def result = []
data.each {
result << it[0]
}
return result
}
For all above code the result will be [1, 11, 21]
If I understand your last comment, this is another way to do:
String[][] citylist(String[][] data) {
String[][] result = new String[data.length][]
for (int i = 0; i < data.length; i++) {
result[i] = new String[1]
result[i][0] = data[i][0]
}
return result
}
Your result will be [[1], [11], [21]]

Related

How To Add values to two-dimensional array with for loops using Google Apps Script

Could someone show me some simple examples to add values with for loops to a two-dimensional array?
My totally wrong test script is below.
Expected behavior:
wholeValues[[0],[0]] = 0, wholeValues[[0],[1]] = 1, wholeValues[[0],[2]] = 2,
wholeValues[[1],[0]] = 0, wholeValues[[1],[1]] = 1, wholeValues[[1],[2]] = 2 .....
function test() {
var wholeValues = [[],[]];
var value = [];
for (var i = 0; i < 5; i++){
for (var j = 0; j < 3; j++) {
wholeValues[[i],[j]] = value[j];
}
}
Logger.log(wholeValues[[0],[1]]);
}
Hope this could help.
function test() {
//2d array
var wholeValues = [];
for (var i = 0; i < 5; i++){
//create a 1D array first with pushing 0,1,2 elements with a for loop
var value = [];
for (var j = 0; j < 3; j++) {
value.push(j);
}
//pushing the value array with [0,1,2] to thw wholeValues array.
wholeValues.push(value);
} // the outer for loop runs five times , so five the 0,1,2 with be pushed in to thewholevalues array by creating wholeValues[0][0],wholeValues[0][1]...till..wholeValues[4][2]
Logger.log(wholeValues[0][1]);
}

Is their a way to find the closest number to 0 in an Array?

I've got an array like that
var tideArray = new Array();
tideArray.push({tide:"haute1", difference: "-14"});
tideArray.push({tide:"haute2", difference: "-3"});
tideArray.push({tide:"basse1", difference: "-9"});
tideArray.push({tide:"basse2", difference: "4"});
tideArray.sortOn("difference", Array.NUMERIC);
trace(tideArray[0].tide);
For now, it's choosing the minimum number (-14) but I'd like to choose the closest number to 0.
Is there a way to do that ?
EDIT
I've tried that :
trace(closestToZero(tideArray));
function closestToZero(a:Array):int
{
var curDelta:int = Math.abs(0 - a[0].difference);
var curIndex:int = 0;
for(var i:int = 1; i < a.length; i++){
var thisDelta:int = Math.abs(0 - a[i].difference);
if(thisDelta < curDelta){
curIndex = i;
}
}
return curIndex;
}
But it seems that there is a mistake somewhere because the trace result is 3 (so it means that it's telling me that "basse2" (4) is the closest to 0... But, as you can see, it's "haute2" (-3) the closest).
I think it would be more efficient to simply loop over the array to find the item with the (absolute) minimum difference value:
if (tideArray.length > 0)
{
var minItem: Object = tideArray[0];
for (var index:int = 1; index < tideArray.length; index++)
{
if (Math.abs(tideArray[index].difference) < Math.abs(minItem.difference))
{
minItem = tideArray[index];
}
}
trace(minItem.tide);
}
Something like this
var tideArray = new Array();
...
function sortMyArray(a,b):int {
if (Math.abs(a) < Math.abs(b)) {
return -1;
}
if (Math.abs(a) > Math.abs(b)) {
return 1;
}
return 0;
}
tideArray.sort(sortMyArray);
Edit :
For your array.
function sortMyArray(a,b):int {
if (Math.abs(a.difference) < Math.abs(b.difference)) {
return -1;
}
if (Math.abs(a.difference) > Math.abs(b.difference)) {
return 1;
}
return 0;
}

I want to collect the common elements in two different arraylist

ArrayList1 = [a,b,c,d]
ArrayList1 = [d,c,e,f,g]
I would like to have result as
ArrayListFinal = [c,d]
How can I accomplish this?
try this...........
for(int i =0;i<list1.size();i++){
for(int j=0;j<list2.size();j++){
if(list.get(j).equals(list2.get(i))){
listfinal.add(list.get(i));
}
}
}
for(int i=0;i<listfinal.size();i++){
System.out.println(list1.get(i));
}
Your problem is to find the intersection (denoted as ∩) of two array A and B .
Suppose the arrays are unsorted. The simplest way is to compare the elements one by one, like this:
function getIntersect(arr1, arr2) {
var temp = [];
for(var i = 0; i < arr1.length; i++){
for(var k = 0; k < arr2.length; k++){
if(arr1[i] == arr2[k]){
temp.push( arr1[i]);
break;
}
}
}
return temp;
}
But if the arr2 is much shorter than arr1, you may using a hash table to speed up:
function getIntersect(arr1, arr2) {
var r = [], o = {}, l = arr2.length, i, v;
for (i = 0; i < l; i++) {
o[arr2[i]] = true;
}
l = arr1.length;
for (i = 0; i < l; i++) {
v = arr1[i];
if (v in o) {
r.push(v);
}
}
return r;
}

finding sequences in AS3 array

does anyone have any idea what to do in order to find the number of sequences in an array?
for example, my array is:
var numbers:Array = new Array(banana, banana, apple, banana, banana);
and i need to find is:
* how many times there is a sequence of "banana"
* and the length of each sequence.
what shell i do in order to get the following result:
2,1,2 (2 bananas, 1 apple, 2 bananas)
i tried with do while loop, but i i guess i miss something.
a short example will be very appreciated!
thanx
var prev:String = null;
var q:int = 0;
var result:Array = new Array();
for(var i:int=0; i<numbers.length; ++i){
if(prev!=numbers[i]){
if(q>0) result.push(q);
q=1;
prev=numbers[i];
}
else ++q;
}
if(q>0) result.push(q);
This is, assuming banana, etc. are strings (probably a typo above?). It would be simple to modify to other types of objects
Really all you want to know is whether the string at index n equals the string at index n+1...
var targetIndex:int = numbers.length - 1;
var results:Array = [1];
var resultsIndex:int = 0;
for(var n:int = 0; n < targetIndex; n++) {
if(numbers[n] == numbers[n+1]) {
results[resultsIndex]++;
} else {
results[++resultsIndex] = 1;
}
}
trace(results.join(','));
function sequencesInArray(array:Array):Array {
var sequence:Array = [];
var currSequenceCount:uint = 1;
for (var i:uint = 1; i < numbers.length; i++) {
if (numbers[i - 1] != numbers[i]) {
sequence.push(currSequenceCount);
currSequenceCount = 1;
} else {
currSequenceCount++;
}
}
return sequence;
}
Then:
var banana:int = 1;
var apple:int = 2;
sequencesInArray([banana, banana, apple, banana, banana]); //returns: [2, 1, 2]
In the question you don't define banana and apple, anyway I would use a map or a Dictionary to store key/value pairs, with the key being the string/object you want to count and the value being the counter of the object occurences in your array.
var objectsCounter:Dictionary = new Dictionary();
for (var key:String in numbers)
{
if ( objectsCounter[key] )
objectsCounter[key] = objectsCounter[key] + 1;
else
objectsCounter[key] = 1;
}
This way you can store any type in the dictionary.
edit:
for (var key:String in objectsCounter)
{
// iterates through each object key
}
for each (var value:Number in objectsCounter)
{
// iterates through each value
}
I believe this is what you're looking for:
var array:Array = [
"banana", "banana",
"apple",
"banana", "banana", "banana"
];
var sequences:Array = findSequences(array, "banana");
trace("sequences:", sequences); // prints "sequences: 2,3"
And:
private function findSequences(array:Array, searchElement:*):Array
{
var sequences:Array = [];
var currentSequence:int = 0;
for each (var element:* in array) {
if (element == searchElement) {
currentSequence++;
} else if (currentSequence > 0) {
sequences.push(currentSequence);
currentSequence = 0;
}
}
if (currentSequence > 0) {
sequences.push(currentSequence);
}
return sequences;
}

Search an array for a string and return the index in AS3

I want to search an array to see if it contains a specific string, and then get the index of the result.
For example, if I had:
array[0] = "dogs";
array[1] = "cats";
array[2] = "oranges";
I want to be able to search for "oran" and get 2 back. Any idea on how to do this?
You can do something like this:
function findInArray(str:String):int {
for(var i:int = 0; i < array.length; i++){
if(array[i] == str){
trace("found it at index: " + i);
return i;
}
}
return -1; //If not found
}
Then whenever you want to find something call it like:
findInArray("oranges"); // Returns 2
To search for a part of the word can pontentially return undesiderd results for bigger lists, but you can do it with the following:
function findInArrayPartially(str:String):int {
for(var i:int = 0; i < array.length; i++){
if(array[i].indexOf(str) > -1){
trace("found it at index: " + i);
return i;
}
}
return -1; //If not found
}
Another way to do it:
var arr:Array = ["dogs", "cats", "oranges", "apples"];
function indexOfSubstring(array:Array, stringToFind:String):int
{
var answer:int = array.indexOf(stringToFind);
if (answer == -1)
{
var separator:String = "|";
var arrayToString:String = array.join(separator);
var indexInString:int = arrayToString.indexOf(stringToFind);
if (indexInString != -1)
{
var shorterStr:String = arrayToString.substring(0, indexInString);
answer = shorterStr.split(separator).length - 1;
}
}
return answer;
}
trace(indexOfSubstring(arr, "oran")); // returns 2
trace(indexOfSubstring(arr, "les")); // returns 3
trace(indexOfSubstring(arr, "ts")); // returns 1
trace(indexOfSubstring(arr, "broom")); // returns -1

Resources