"A",1,2,3,4
"B",1,2,3,4
"C",1,2,3,4
I want to transpose and get the output as
"A""B""C"
111
222
333
444
Hi sai kiran bandari !
Please provide more information for your next question.
I expect you to have a 2 dimension array for which i made a solution. You want to iteratoe through the array using 2 loops and split the values to a new 2 dimension array according to first array index i in this case.
const data =[['A', 1,2,3,4], ['B', 1,2,3,4], ['C', 1,2,3,4]]
const transposed = []
// iterate through 2 dimension array..
for(var i = 0; i < data.length; i++) {
var arr = data[i]
// Iterate through inner araray
for(let p = 0; p < arr.length; p++) {
// create new inner array if there is not already one at destination..
if(Array.isArray(transposed[p]) === false) {
transposed[p] = []
}
// we want to take all the values of the first array and split it
// up to a single array each. In the second iteration, alle the
// values will be splitted again and you have your transpose.
transposed[p].push(arr[p])
}
}
console.log(transposed)
/* Output => [
[ 'A', 'B', 'C' ],
[ 1, 1, 1 ],
[ 2, 2, 2 ],
[ 3, 3, 3 ],
[ 4, 4, 4 ]
]
*/
Related
In Polars, I'm seeing a return result different than what I would expect when using slicing with series and trying to get the offsets.
I'm creating a Series, then slicing it:
// Make a vec of 3 items, called foo, bar baz
let string_values: Vec<&str> = vec!["foo", "bar", "baz"];
// Add it to a series, this is without dataframes
let series = Series::new("string_values", string_values);
//shape: (3,)
// Series: 'string_values' [str]
// [
// "foo"
// "bar"
// "baz"
// ]
println!("{:?}", series);
This returns a new series.
I can then using downcast_iter() to get the offsets:
// Now we should be able to downcast iter to get the offsets.
// returns [0, 3, 6, 9]
// 0-3 = foo
// 3-6 = bar
// 6-9 = baz
series.utf8().unwrap().downcast_iter().for_each(|array| {
println!("{:?}", array.offsets());
});
Great so far.
I then slice it:
//shape: (2,)
// Series: 'string_values' [str]
// [
// "bar"
// "baz"
// ]
let series_slice = series.slice(1, 2);
println!("{:?}", series_slice);
This returns the correct values.
I then try and use downcast_iter() again:
// Now we should be able to downcast iter to get the offsets for the slice.
// This returns [3, 6, 9]
// Is "foo" still referenced?
series_slice.utf8().unwrap().downcast_iter().for_each(|array| {
println!("{:?}", array.offsets());
});
It returns 3, 6, 9. Why is 9 returned? The length of the series is 6.
Buffers in arrow can be shared. Besides the data they also have an offset and a length.
You original arrow string array contains of the following data:
data: foobarbaz
offsets: 0, 3, 6, 9
offset: 0
length: 3
Retrieving element i uses the following algorithm in pseudocode:
let offset = array.offset
let start_index = offsets[offset + i]
let end_index = offsets[offset + i + 1]
let string_value = data[start_index..end_index]
When you slice an array, we don't copy any data. We only update the offset and the length such that we have all information to represent the sliced array:
data: foobarbaz
offsets: 0, 3, 6, 9
offset: 1
length: 2
I have 2 arrays which both containing strings, for example:
a = ['a', 'b', 'a']
b = ['b', 'a', 'a']
I have found that I can use lodash with:
_.isEmpty(_.xor(a,b))
to make sure they both equal.
However this method seems to fail if I have duplicated values in the arrays, for example:
a = ['a', 'b', 'a']
b = ['b', 'a']
the above method will return true for this case (it will print they are equal) although I have 2 'a' in a array and only 1 in b.
Any elegant ways to perform this comparison?
function isEqual(a, b) {
return [...new Set(a.concat(b)] // Get an array of unique elements of both arrays
.filter(t =>
// Filter on those elements whose count in both arrays is different
a.filter(at=>at===t).length !== b.filter(bt=>bt===t).length
)
.length === 0
}
console.log(['a','b'], ['b','a','a'], isEqual(['a','b'], ['b','a','a']))
console.log(['a','b','a'], ['b','a','a'], isEqual(['a','b','a'], ['b','a','a']))
I propose the following if you don't want to sort the array. You take the one array and remove each item from the other. If an item cannot be removed at any time or the array remains with any items in the end, they are not equal.
var a = ['a', 'b', 'a']
var b = ['b', 'a', 'a']
function areEqual(a, b) {
var flag = true;
b.forEach((letter) => {
let i = a.indexOf(letter);
if(i == -1) { flag = false; }
else a.splice(i, 1);
});
if(flag && a.length == 0) { return true; }
else { return false; }
}
console.log(areEqual(a,b));
Let's say I have a list of numbers: 2, 2, 5, 7
Now the result of the algorithm should contain all possible sums.
In this case: 2+2, 2+5, 5+7, 2+2+5, 2+2+5+7, 2+5+7, 5+7
I'd like to achieve this by using Dynamic Programming. I tried using a matrix but so far I have not found a way to get all the possibilities.
Based on the question, I think that the answer posted by AT-2016 is correct, and there is no solution that can exploit the concept of dynamic programming to reduce the complexity.
Here is how you can exploit dynamic programming to solve a similar question that asks to return the sum of all possible subsequence sums.
Consider the array {2, 2, 5, 7}: The different possible subsequences are:
{2},{2},{5},{7},{2,5},{2,5},{5,7},{2,5,7},{2,5,7},{2,2,5,7},{2,2},{2,7},{2,7},{2,2,7},{2,2,5}
So, the question is to find the sum of all these elements from all these subsequences. Dynamic Programming comes to the rescue!!
Arrange the subsequences based on the ending element of each subsequence:
subsequences ending with the first element: {2}
subsequences ending with the second element: {2}, {2,2}
subsequences ending with the third element: {5},{2,5},{2,5},{2,2,5}
subsequences ending with the fourth element: {7},{5,7},{2,7},{2,7},{2,2,7},{2,5,7},{2,5,7},{2,2,5,7}.
Here is the code snippet:
The array 's[]' calculates the sums for 1,2,3,4 individually, that is, s[2] calculates the sum of all subsequences ending with third element. The array 'dp[]' calculates the overall sum till now.
s[0]=array[0];
dp[0]=s[0];
k = 2;
for(int i = 1; i < n; i ++)
{
s[i] = s[i-1] + k*array[i];
dp[i] = dp[i-1] + s[i];
k = k * 2;
}
return dp[n-1];
This is done in C# and in an array to find the possible sums that I used earlier:
static void Main(string[] args)
{
//Set up array of integers
int[] items = { 2, 2, 5, 7 };
//Figure out how many bitmasks is needed
//4 bits have a maximum value of 15, so we need 15 masks.
//Calculated as: (2 ^ ItemCount) - 1
int len = items.Length;
int calcs = (int)Math.Pow(2, len) - 1;
//Create array of bitmasks. Each item in the array represents a unique combination from our items array
string[] masks = Enumerable.Range(1, calcs).Select(i => Convert.ToString(i, 2).PadLeft(len, '0')).ToArray();
//Spit out the corresponding calculation for each bitmask
foreach (string m in masks)
{
//Get the items from array that correspond to the on bits in the mask
int[] incl = items.Where((c, i) => m[i] == '1').ToArray();
//Write out the mask, calculation and resulting sum
Console.WriteLine(
"[{0}] {1} = {2}",
m,
String.Join("+", incl.Select(c => c.ToString()).ToArray()),
incl.Sum()
);
}
Console.ReadKey();
}
Possible outputs:
[0001] 7 = 7
[0010] 5 = 5
[0011] 5 + 7 = 12
[0100] 2 = 2
This is not an answer to the question because it does not demonstrate the application of dynamic programming. Rather it notes that this problem involves multisets, for which facilities are available in Sympy.
>>> from sympy.utilities.iterables import multiset_combinations
>>> numbers = [2,2,5,7]
>>> sums = [ ]
>>> for n in range(2,1+len(numbers)):
... for item in multiset_combinations([2,2,5,7],n):
... item
... added = sum(item)
... if not added in sums:
... sums.append(added)
...
[2, 2]
[2, 5]
[2, 7]
[5, 7]
[2, 2, 5]
[2, 2, 7]
[2, 5, 7]
[2, 2, 5, 7]
>>> sums.sort()
>>> sums
[4, 7, 9, 11, 12, 14, 16]
I have a solution that can print a list of all possible subset sums.
Its not dynamic programming(DP) but this solution is faster than the DP approach.
void solve(){
ll i, j, n;
cin>>n;
vector<int> arr(n);
const int maxPossibleSum=1000000;
for(i=0;i<n;i++){
cin>>arr[i];
}
bitset<maxPossibleSum> b;
b[0]=1;
for(i=0;i<n;i++){
b|=b<<arr[i];
}
for(i=0;i<maxPossibleSum;i++){
if(b[i])
cout<<i<<endl;
}
}
Input:
First line has the number of elements N in the array.
The next line contains N space-separated array elements.
4
2 2 5 7
----------
Output:
0
2
4
5
7
9
11
12
14
16
The time complexity of this solution is O(N * maxPossibleSum/32)
The space complexity of this solution is O(maxPossibleSum/8)
I have two arrays of integer type.
int[] righttarray=new int[] {6,9,8,1,5,3};
int[] leftarray=new int[] {1,3};
Now I have to find out the common elements between these two as well as I need to match common elements indexes. If the indexes are same then its ok, if not then sequence will be maintained from rightarray.
I am getting Common elements by intersect method in C#.
See, element 1 and 3 are common in both the arrays. But in "leftarray" their sequence in 0,1 and in "rightarray" their sequence in 3,5. How to check this is my question. Thanks !!
Help me out doing this.
Ok, try something like:
int[] righttarray = new int[] { 6, 3, 8, 1, 5, 3 };
int[] leftarray = new int[] { 1, 3 };
if (righttarray.Length < leftarray.Length)
{
var result = righttarray.Where((x, i) => righttarray[i] == leftarray[i]);
}
else
{
var result = leftarray.Where((x, i) => leftarray[i] == righttarray[i]);
}
This will give you the number 3, which is in the same index and with the same element number. In your example, the output will be empty, I have changed only to check it ;)
I have a pair of strings, for example: abcabcabc and abcxxxabc and a List of Common Substring Pairs (LCSP), in this case LCSP is 6 pairs, because three abc in the first string map to two abc in the second string. Now I need to find the longest valid (incrementing) sequence of pairs, in this case there are three equally long solutions: 0:0,3:6; 0:0,6:6; 3:0,6:6 (those numbers are starting positions of each pair in the original strings, the length of substrings is 3 as length of "abc"). I would call it the Longest Substring Pair Sequence or LSPQ. (Q is not to confuse String and Sequence)
Here is the LCSP for this example:
LCSP('abcabcabc', 'abcxxxabc') =
[ [ 6, 6, 3 ],
[ 6, 0, 3 ],
[ 3, 6, 3 ],
[ 0, 6, 3 ],
[ 3, 0, 3 ],
[ 0, 0, 3 ] ]
LSPQ(LCSP('abcabcabc', 'abcxxxabc'), 0, 0, 0) =
[ { a: 0, b: 0, size: 3 }, { a: 3, b: 6, size: 3 } ]
Now I find it with brute force recursively trying all combinations. So I am limited to about 25 pairs, otherwise it is unpractical. Size=[10,15,20,25,26,30], Time ms = [0,15,300,1000,2000,19000]
Is there a way to do that in linear time or at least not quadratic complexity so that longer input LCSP (List of Common Substring Pairs) could be used.
This problem is similar to the "Longest Common Subsequence", but not exactly it, because the input is not two strings but a list of common substrings sorted by their length. So I do not know where to look for an existing solutions or even if they exist.
Here is my particular code (JavaScript):
function getChainSize(T) {
var R = 0
for (var i = 0; i < T.length; i++) R += T[i].size
return R
}
function LSPQ(T, X, Y, id) {
// X,Y are first unused character is str1,str2
//id is current pair
function findNextPossible() {
var x = id
while (x < T.length) {
if (T[x][0] >= X && T[x][1] >= Y) return x
x++
}
return -1
}
var id = findNextPossible()
if (id < 0) return []
var C = [{a:T[id][0], b:T[id][1], size:T[id][2] }]
// with current
var o = T[id]
var A = C.concat(LSPQ(T, o[0]+o[2], o[1]+o[2], id+1))
// without current
var B = LSPQ(T, X, Y, id+1)
if (getChainSize(A) < getChainSize(B)) return B
return A
}