How to make pairs from Range? - grouping

I have got range MySQLTablesRange. It's consist data like:
aa_1 aa_3 aa_2 bb_2 bb_1 bb_3
I need to create pairs like:
aa_1 bb_1
aa_2 bb_2
aa_3 bb_3
std.algorithm have method group that doing similar thing, but I do not know how to write it in code. I did:
MySQLTablesRange.each!(a => a.split("_")[1].array.group.writeln);
But it's wrong, because group works with array, but not with single element.
Any ideas?

Update: After testing this - I realised it's not 'group' you want. But chunkBy. Updated the answer to reflect that.
https://dlang.org/phobos/std_algorithm_iteration.html#chunkBy
You have to tell chunkBy how to chunk the data...
[1,2,3,4,5,6]
.sort!((a,b) => a%2 > b%2) // separate odds n evens
.chunkBy!((a,b) => a%2 == b%2); // chunk them so all evens are in one range, odds in another.
That will create two groups. One with odd numbers, one with evens.
In your case it looks like you'd group them on the text that comes after '_' in each element.
"aa_1 aa_2 aa_3 bb_1 bb_2 bb_3 cc_1"
.split(" ")
.sort!((a,b) => a[$-1].to!int < b[$-1].to!int) // sort it so _1's are together, _2s are together. etc
.chunkBy!((a,b) => a[$-1] == b[$-1]) // chunk them so they're in they're own range
.each!writeln; // print each range
$ rdmd test.d
["aa_1", "bb_1", "cc_1"]
["aa_2", "bb_2"]
["aa_3", "bb_3"]
Ideally you'd get index of _ and compare after that...

Related

Understanding; for i in range, x,y = [int(i) in i.... Python3

I am stuck trying to understand the mechanics behind this combined input(), loop & list-comprehension; from Codegaming's "MarsRover" puzzle. The sequence creates a 2D line, representing a cut-out of the topology in an area 6999 units wide (x-axis).
Understandably, my original question was put on hold, being to broad. I am trying to shorten and to narrow the question: I understand list comprehension basically, and I'm ok experienced with for-loops.
Like list comp:
land_y = [int(j) for j in range(k)]
if k = 5; land_y = [0, 1, 2, 3, 4]
For-loops:
for i in the range(4)
a = 2*i = 6
ab.append(a) = 0,2,4,6
But here, it just doesn't add up (in my head):
6999 points are created along the x-axis, from 6 points(x,y).
surface_n = int(input())
for i in range(surface_n):
land_x, land_y = [int(j) for j in input().split()]
I do not understand where "i" makes a difference.
I do not understand how the data "packaged" inside the input. I have split strings of integers on another task in almost exactly the same code, and I could easily create new lists and work with them - as I understood the structure I was unpacking (pretty simple being one datatype with one purpose).
The fact that this line follows within the "game"-while-loop confuses me more, as it updates dynamically as the state of the game changes.
x, y, h_speed, v_speed, fuel, rotate, power = [int(i) for i in input().split()]
Maybe someone could give an example of how this could be written in javascript, haskell or c#? No need to be syntax-correct, I'm just struggling with the concept here.
input() takes a line from the standard input. So it’s essentially reading some value into your program.
The way that code works, it makes very hard assumptions on the format of the input strings. To the point that it gets confusing (and difficult to verify).
Let’s take a look at this line first:
land_x, land_y = [int(j) for j in input().split()]
You said you already understand list comprehension, so this is essentially equal to this:
inputs = input().split()
result = []
for j in inputs:
results.append(int(j))
land_x, land_y = results
This is a combination of multiple things that happen here. input() reads a line of text into the program, split() separates that string into multiple parts, splitting it whenever a white space character appears. So a string 'foo bar' is split into ['foo', 'bar'].
Then, the list comprehension happens, which essentially just iterates over every item in that splitted input string and converts each item into an integer using int(j). So an input of '2 3' is first converted into ['2', '3'] (list of strings), and then converted into [2, 3] (list of ints).
Finally, the line land_x, land_y = results is evaluated. This is called iterable unpacking and essentially assumes that the iterable on the right has exactly as many items as there are variables on the left. If that’s the case then it’s just a nice way to write the following:
land_x = results[0]
land_y = results[1]
So basically, the whole list comprehension assumes that there is an input of two numbers separated by whitespace, it then splits those into separate strings, converts those into numbers and then assigns each number to a separate variable land_x and land_y.
Exactly the same thing happens again later with the following line:
x, y, h_speed, v_speed, fuel, rotate, power = [int(i) for i in input().split()]
It’s just that this time, it expects the input to have seven numbers instead of just two. But then it’s exactly the same.

Iterate over an existing map against a list of tuples scala

I have a list of tuples that I must change the values for in a map that contains those tuples. So if I have a list such as List((0,2), (0,3)) with a map that looks like this: Map((0,2) => List(1,2,3), (0,3) => List(1,2)), I need to access the matching map tuples with the tuples listed in the list, then remove a number from the mapping.
So in the example above, if I wanted to remove 2 from the mapping, I would get Map((0,2) => List(1,3), (0,3) => List(1)).
Design wise, I was thinking of pattern matching the map, but I've read some answers that said that may not be the best way. The tough part for me is that it has to be immutable, so I was thinking of pattern matching the list, getting the map value, change the value, then recreate the map and recursively call the function again. What do you think of this implementation?
This could be a way to remove 2 from your Map:
val newMap = oldMap.mapValues(list => list.filter(_ != 2))
Or more generally:
def filterInMap(element: Int, oldMap: Map[(Int,Int),List[Int]]) =
oldMap.mapValues(list => list.filter(_ != element))
This way there's no need to mutate anything at all. mapValues transforms just the values of your Map and returns a copy of the original without mutating it at all. filter then gets the job done by only allowing elements that don't match the element we would like to remove.
Bonus: even more generally:
def filterInMap[A](element: A, oldMap: Map[(A,A),List[A]]) =
oldMap.mapValues(list => list.filter(_ != element))

How to read each element within a tuple from a list

I want to write a program which will read in a list of tuples, and in the tuple it will contain two elements. The first element can be an Object, and the second element will be the quantity of that Object. Just like: Mylist([{Object1,Numbers},{Object2, Numbers}]).
Then I want to read in the Numbers and print the related Object Numbers times and then store them in a list.
So if Mylist([{lol, 3},{lmao, 2}]), then I should get [lol, lol, lol, lmao, lmao] as the final result.
My thought is to first unzip those tuples (imagine if there are more than 2) into two tuples which the first one contains the Objects while the second one contains the quantity numbers.
After that read the numbers in second tuples and then print the related Object in first tuple with the exact times. But I don't know how to do this. THanks for any help!
A list comprehension can do that:
lists:flatten([lists:duplicate(N,A) || {A, N} <- L]).
If you really want printing too, use recursion:
p([]) -> [];
p([{A,N}|T]) ->
FmtString = string:join(lists:duplicate(N,"~p"), " ")++"\n",
D = lists:duplicate(N,A),
io:format(FmtString, D),
D++p(T).
This code creates a format string for io:format/2 using lists:duplicate/2 to replicate the "~p" format specifier N times, joins them with a space with string:join/2, and adds a newline. It then uses lists:duplicate/2 again to get a list of N copies of A, prints those N items using the format string, and then combines the list with the result of a recursive call to create the function result.

how reduce RDD work in Apache Spark

Am currently working with Apache Spark.
But i can not understand how reduce work after map ..
my example is pretty simple
val map = readme.map(line => line.split(" ").size)
i know this will return array of number of words per line but where is the key/value here to pass a reduce function ..
map.reduce((a,b) => {if(a>b) a else b})
reduce phase how it works .. (a,b) is the tuple_2 ? or its key/value from map function ??
Once you have
val map = readme.map(line => line.split(" ").size)
Each element of the RDD consists of a single number, the number of words in a line of the file.
You could count all the words in your dataset with map.sum() or map.reduce( (a,b) => a+b ), which are equivalent.
The code you have posted:
map.reduce((a,b) => {if(a>b) a else b})
would find the maximum number of words per line for your entire dataset.
The RDD.reduce method works by converting every two elements it encounters, which at first are taken from pairs of RDD rows, to another element, in this case a number. The aggregation function should be written so it can be nested and called on the rows in any order. For example, subtraction will not yield useful results as a reduce function because you can not predict ahead of time in what order results would be subtracted from one another. Addition, however, or maximization, still works correctly no matter the order.

Splitting a list of strings into 2 lists, one containing single values and the other multiples

I have a large list of strings, it's a TStringList and is sorted by key. The structure is ('Key', Obj).
In this list there are single and repeated key values. I'm trying to split them into two separate lists, one for the single values and one for the repeated ones.
If my initial list is {A,A,A,B,B,C,D,E,E,F} then the result should be a list of singles = {C,D,F} and a list of repeats = {A,B,E}.
I've tried many different variations of the same code to try and get it to work but I'm having problems, a lot of them. :)
I'm getting key[i] and key[i+1] and comparing them, if they're the same I save [i+1] into a temp string and set a bool value, I then run some conditional checks to determine what list it should go in but just failing at the moment.
It seems like it should be such an easy thing to accomplish and I am somewhat embarrassed to have to ask. Any help is greatly appreciated, thank you.
StartIndex := 0;
for i := 1 to List.Count - 1 do
if List[i].Key <> List[StartIndex].Key then begin
if i - StartIndex = 1 then
SingleList.Add(List[StartIndex])
else
MultiList.Add(List[StartIndex])
StartIndex := i;
end;
//check for the last chunk
if StartIndex = List.Count - 1 then
SingleList.Add(List[StartIndex])
else
MultiList.Add(List[StartIndex])
I suspect that the mistake you're making is that you don't select correct index for the next comparision in case key[i] = key[i+1]. So if input is A,A,A,B,B you first compare i := 0 => [0]=[1] (you compare first two A) which is True. Then you probably proceed with i := 2 which means that you compare last A to the first B which causes the bug. Solution is to move index to the next value after last key witch equals to the current matching key, ie something like
while(list.Count > i)and(list.keys[i] = currentKey)do Inc(i);
at the appropriate place should make sure that you make next key comparision with correct list items.