Scala: Using a value from an array to search in another array - arrays

I have two arrays:
GlobalArray:Array(Int,Array[String]) and SpecificArray:Array(Int,Int).
The first Int in both of them is a key and I would like to get the element corresponding to that key from the GlobalArray.
In pseudocode:
val v1
For each element of SpecificArray
Get the corresponding element from GlobalArray to use its Array[String]
If (sum <= 100)
for each String of the Array
update v1
// ... some calculation
sum += 1
println (v1)
I know using .map() I could go through each position of the SpecificArray, but so far I was able to do this:
SpecificArray.map{x => val in_global = GlobalArray.filter(e => (e._1 == x._1))
// I don't know how to follow
}

How about something like below, I would prefer to for comprehension code which has better readability.
var sum:Int = 0
var result:String = ""
for {
(k1,v1) <- SpecificArray //v1 is the second int from specific array
(k2,values) <- GlobalArray if k1 == k2 //values is the second array from global array
value <- values if sum < 100 //value is one value frome the values
_ = {sum+=1; result += s"(${v1}=${value})"} //Update something here with the v1 and value
} yield ()
println(result)

Note needs more optimization
Convert GlobalArray to Map for faster lookup.
val GlobalMap = GlobalArray.toMap
SpecificArray.flatMap(x => GlobalMap(x._1))
.foldLeft(0)((sum:Int, s:String) => {
if(sum<=100) {
// update v1
// some calculation
}
sum+1
})
If not all keys of SpecificArray is present in GlobalMap then use GlobalMap.getOrElse(x._1, Array())

How sum affects the logic and what exactly is v1 is not clear from your code, but it looks like you do search through GlobalArray many times. If this is so, it makes sense to convert this array into a more search-friendly data structure: Map. You can do it like this
val globalMap = GlobalArray.toMap
and then you may use to join the strings like this
println(SpecificArray.flatMap({case (k,v) => globalMap(k).map(s => (k,v,s))}).toList)
If all you need is strings you may use just
println(SpecificArray.flatMap({case (k,v) => globalMap(k)}).toList)
Note that this code assumes that for every key in the SpecificArray there will be a matching key in the GlobalArray. If this is not the case, you should use some other method to access the Map like getOrElse:
println(SpecificArray.flatMap({case (k,v) => globalMap.getOrElse(k, Array()).map(s => (k,v,s))}).toList)
Update
If sum is actually count and it works for whole "joined" data rather than for each key in the SpecificArray, you may use take instead of it. Code would go like this:
val joined = SpecificArray2.flatMap({case (k,v) => globalMap.getOrElse(k, Array()).map(s => (s,v))})
.take(100) // use take instead of sum
And then you may use joined whatever way you want. And updated demo that builds v1 as joined string of form v1 += String_of_GlobalArray + " = " + 2nd_Int_of_SpecificArray is here. The idea is to use mkString instead of explicit variable update.

Related

How prevent Object.keys() sort?

The problem with the ECMA standard for sort of Object.keys() is known:
Object.keys() handle all keys with integer (example: 168), including integer as strings (example: "168"), as a integer. The result is, both are the same (168 === "168"), and overwrite itself.
var object = {};
object["168"] = 'x';
object[168] = 'y';
Object.keys(object); // Array [ "168" ]
object[Object.keys(object)]; // "y"
Interestingly, all keys (including pure integer keys) are returned as a string.
The ecma262 wrote about this: All keys will be handle as a integer, expect the key is a String but is not an array index.
https://tc39.es/ecma262/#sec-ordinaryownpropertykeys
That should tell us: 168 === "168". A toString() do not solve the problem.
var object = {};
object[[3].toString()] = 'z';
object[[1].toString()] = 'x';
object[[2].toString()] = 'y';
Object.keys(object);
// Array(3) [ "1", "2", "3" ]
Paradoxically, in this case, only integer apply as "enumerable" (it's ignoring array.sort(), that sort also strings with letters.).
My question about this is simple: How can i prevent the sort function in Object.keys()? I have testet the Object.defineProperties(object, 1, {value: "a", enumerable: true/false}), but that mean not realy enumerable in the case of integer or string or integer-like string. It means only should it be counted with or not. It means "counted" like omit (if it false), not "enumerabled" like ascending or descending.
A answere like that is not a good answer: Please use only letters [a-zA-Z] or leastwise a letter at the first position of keyword.
What I want: That the keys are not sorted, but output in the order in which they were entered, whether integer, string or symbol.
Disclaimer: Please solutions only in JavaScript.
Javascript Objects are unordered by their nature. If you need an ordered object-like variable I would suggest using a map.
To achieve what you're looking for with a map instead of object you'd do something like the below:
var map1 = new Map();
map1.set("123", "c");
map1.set(123, "b");
var iterator1 = map1.keys();
var myarray = [];
for (var i = 0; i < map1.size; i++) {
myarray.push(iterator1.next().value);
}
console.log(myarray);
// Array ["123", 123]
Unfortunately it's not compatible with IE and I'm not sure how else you could achieve what you need without it. A quick Google did return something about jQuery maps, though.
If you don't want to use jQuery and still need to support IE some points are below:
Is there anything stopping you using an array rather than JS object to store the data you need? This will retain the order per your requirements unlike objects. You could have an object entry in each iteration which represents the key then use a traditional foreach to obtain them as an array. I.e.
The array:
var test_array = [
{key: 123, value: 'a value here'},
{key: "123", value: 'another value here'}
];
// console.log(test_array);
Getting the keys:
var test_array_keys = [];
test_array.forEach(function(obj) { test_array_keys.push(obj['key']); } );
// console.log(test_array_keys);
Then if you needed to check whether the key exists before adding a new entry (to prevent duplicates) you could do:
function key_exists(key, array)
{
return array.indexOf(key) !== -1;
}
if(key_exists('12345', test_array_keys))
{
// won't get here, this is just for example
console.log('Key 12345 exists in array');
}
else if(key_exists('123', test_array_keys))
{
console.log('Key 123 exists in array');
}
Would that work? If not then the only other suggestion would be keeping a separate array alongside the object which tracks the keys and is updated when an entry is added or removed to/from the object.
Object Keys sorted and store in array
First Creating student Object. then sort by key in object,last keys to store in array
const student={tamil:100, english:55, sci:85,soc:57}
const sortobj =Object.fromEntries(Object.entries(student).sort())
console.log(Object.keys(sortobj))
use map instead of an object.
let map = new Map()
map.set("a", 5)
map.set("d", 6)
map.set("b", 12)
to sort the keys (for example, to update a chart data)
let newMap = new Map([...map.entries()].sort())
let keys = Array.from(newMap.keys()) // ['a','b','d']
let values = Array.from(newMap.values()) // [5,12,6]

Kotlin - Find matching objects in array

Let's say I have an array of strings and I want to get a list with objects that match, such as:
var locales=Locale.getAvailableLocales()
val filtered = locales.filter { l-> l.language=="en" }
except, instead of a single value I want to compare it with another list, like:
val lang = listOf("en", "fr", "es")
How do I do that? I'm looking for a one-liner solution without any loops. Thanks!
Like this
var locales = Locale.getAvailableLocales()
val filtered = locales.filter { l -> lang.contains(l.language)}
As pointed out in comments, you can skip naming the parameter to the lambda, and use it keyword to have either of the following:
val filtered1 = locales.filter{ lang.contains(it.language) }
val filtered2 = locales.filter{ it.language in lang }
Just remember to have a suitable data structure for the languages, so that the contains() method has low time complexity like a Set.

Best way to find needed element in array of objects

I have array of objects of my class. My class have variable for name that is unique for every object created. Now, I want to find, say, object in array that has a name "test". I wanted to try something like creating second array with just names as elements and when I create new object in my first array to create object in second array so that they share index number. Something like this:
arrayOfObjects.push(new obj("test"));
arrayOfNames.push("test");
function findIndexNumberOf(name){
for(var i = 0; i < arrayOfNames.length; i++){
if(arrayOfNames[i] === name)
return i;
}
}
But I think that this is pretty robust solution so I'm wondering is there better/smarter/faster way of doing this.
If you want to find the index of an item, it's generally the easiest to use indexOf:
const haystack = ["this", "is", "a", "test"];
const needle = "this";
const result = haystack.indexOf(needle);
However, this will work with primitive types. Assuming you have an array of objects, comparing them will require a different approach. Here are some one-liners:
const haystack = [new String("this"), new String("is"), new String("a"), new String("test")];
const needle = "test";
const result1 = haystack.indexOf(haystack.filter(item => item == needle)[0]);
const result2 = haystack.indexOf(haystack.filter(item => item.toString() === needle.toString())[0]);
const result3 = haystack.map(item => item.toString()).indexOf(needle.toString());
const result4 = haystack.indexOf(haystack.find(item => item.toString() === needle.toString()));
result1 filters the haystack using the == operator, thus ignoring the fact that the compared values are actually different types. The first element of the filtered array is then fed to indexOf. This will allow you to use a primitive string as the needle and search through a haystack of objects.
result2 uses the same approach, but casts both compared values to a primitive string, making sure they're both of the same type. This will allow you to mix and match primitives and String objects liberally, both in the haystack and needle.
result3 maps all haystack values to primitive strings and then uses indexOf on that new array of primitives. I also added toString to the needle to ensure it's also a primitive. This works similar to your approach, but the mapping is run every time you search for a needle. This is probably suboptimal.
result4 uses Array.prototype.find to locate the target object on the haystack and then feeds the result to indexOf. This might be the fastest, but I have no empirical data to back this up.
Now, in case you wanted to find the actual item, not just its index, you're best off using Array.prototype.find:
const result = haystack.find(item => item == needle);
or, in case both are String objects:
const result = haystack.find(item => item.toString() === needle.toString());
You can use the find method of Arrays object:
const myObject = arr.find(o => o.name === 'the_name_you_search');

Scala Converting Each Array Element to String and Splitting

I have an array loaded in, and been playing around in the REPL but can't seem to get this to work.
My array looks like this:
record_id|string|FALSE|1|
offer_id|decimal|FALSE|1|1,1
decision_id|decimal|FALSE|1|1,1
offer_type_cd|integer|FALSE|1|1,1
promo_id|decimal|FALSE|1|1,1
pymt_method_type_cd|decimal|FALSE|1|1,1
cs_result_id|decimal|FALSE|1|1,1
cs_result_usage_type_cd|decimal|FALSE|1|1,1
rate_index_type_cd|decimal|FALSE|1|1,1
sub_product_id|decimal|FALSE|1|1,1
campaign_id|decimal|FALSE|1|1,1
When I run my command:
for(i <- 0 until schema.length){
val convert = schema(i).toString;
convert.split('|').drop(2);
println(convert);
}
It won't drop anything. It also is not splitting it on the |
Strings are immutable, and so split and drop don't mutate the string - they return a new one.
You need to capture the result in a new val
val split = convert.split('|').drop(2);
println(split.mkString(" "));
Consider also defining a lambda function for mapping each item in the array, where intermediate results are passed on with the function,
val res = schema.map(s => s.toString.split('|').drop(2))

How do I remove duplicate values from my Multidimensional array in a Scala way?

I'm trying extract some values from a String. The string contains several lines with values. The values on each line are number, firstname, last name. Then I want to filter by a given pattern and remove the duplicate numbers.
This is my test:
test("Numbers should be unique") {
val s = Cool.prepareListAccordingToPattern(ALLOWED_PATTERN, "1234,örjan,nilsson\n4321,eva-lisa,nyman\n1234,eva,nilsson")
assert(s.length == 2, "Well that didn't work.. ")
info("Chopping seems to work. Filtered duplicate numbers. Expected 1234:4321, got: "+s(0)(0)+":"+s(1)(0))
}
The methods:
def prepareListAccordingToPattern(allowedPattern: String, s: String) : Array[Array[String]] = {
val lines = chop("\n", s)
val choppedUp = lines.map(line =>
chop(",", line)).filter(array =>
array.length == 3 && array(0).matches(allowedPattern)
)
choppedUp
}
def chop(splitSymbol: String, toChop: String) : Array[String] = {
toChop.split(splitSymbol)
}
My test fails as expected since I receive back a multidimensional array with duplicates:
[0]["1234","örjan","nilsson"]
[1]["4321","eva-lisa","nyman"]
[2]["1234","eva","nilsson"]
What I would like to do is to filter out the duplicated numbers, in this case "1234"
so that I get back:
[0]["1234","örjan","nilsson"]
[1]["4321","eva-lisa","nyman"]
How should I do this in a scala way? Maybe I could attack this problem differently?
val arr = Array(
Array("1234","rjan","nilsson"),
Array("4321","eva-lisa","nyman"),
Array("1234","eva","nilsson")
)
arr.groupBy( _(0)).map{ case (_, vs) => vs.head}.toArray
// Array(Array(1234, rjan, nilsson), Array(4321, eva-lisa, nyman))
If you have a collection of elements (in this case Array of Array[String]) and want to get single element with every value of some property (in this case property is the first string from Array[String]) you should group elements of collection based on this property (arr.groupBy( _(0))) and then somehow select one element from every group. In this case we picked up the first element (Array[String]) from every group.
If you want to select any (not necessary first) element for every group you could convert every element (Array[String]) to the key-value pair ((String, Array[String])) where key is the value of target property, and then convert this collection of pairs to Map:
val myMap = arr.map{ a => a(0) -> a }.toMap
// Map(1234 -> Array(1234, eva, nilsson), 4321 -> Array(4321, eva-lisa, nyman))
myMap.values.toArray
// Array(Array(1234, eva, nilsson), Array(4321, eva-lisa, nyman))
In this case you'll get the last element from every group.
A bit implicit, but should work:
val arr = Array(
Array("1234","rjan","nilsson"),
Array("4321","eva-lisa","nyman"),
Array("1234","eva","nilsson")
)
arr.view.reverse.map(x => x.head -> x).toMap.values
// Iterable[Array[String]] = MapLike(Array(1234, rjan, nilsson), Array(4321, eva-lisa, nyman))
Reverse here to override "eva","nilsson" with "rjan","nilsson", not vice versa

Resources