Inserting/adding from one arraylist into two arraylist - linq

I'm looking a way to insert arraylist in two different arraylist with same number of items.
for an example:
I have ArrayList something like this
ArrayList mainArrayList = new ArrayList {1, 2, 3,4,5,6};
So what I want from mainArrayList to insert into two arraylist (arraylist1 and arraylist 2)
this is what i am looking to have in two arraylist:
ArrayList arrayList1 = new ArrayList {1, 2, 3};
ArrayList arrayList2 = new ArrayList {4, 5, 6};
I can do through for loop but i am sure there is better of doing this.
for (int i = 0; i < mainArrayList.Count; i++)
{
if(arraylist1.Count <3) {
arrayList1.Add(mainArrayList[i]);
}
if(arrayList1.Count >3)
{
arrayList2.Add(mainArrayList[i]);
}
}

Use List<T> instead of ArrayList which is an old non-generic container. Then you can use GetRange():
List<int> mainList = new List<int> {1, 2, 3, 4, 5, 6};
List<int> list1 = mainList.GetRange(0, 3);
List<int> list2 = mainList.GetRange(3, 3);

Use GetRange(from, length)
ArrayList mainArrayList = new ArrayList { 1, 2, 3, 4, 5, 6 };
ArrayList arrayList1 = mainArrayList.GetRange(0, 3);
ArrayList arrayList2 = mainArrayList.GetRange(3, 3);

Related

How to generate row-wise permutations of a 2d Array?

I recently got this question (paraphrased below) in a practice interview test and it still stumps me:
Given a 2d array A, generate a list of row-wise 1d array permutations from it.
A = [
[1],
[5, 2],
[6]
]
Answer: [[1, 5, 2, 6], [1, 6, 5, 2], [5, 2, 1, 6], [5, 2, 6, 1], [6, 1, 5, 2], [6, 5, 2, 1]]
Explanation of answer: We are permuting on the rows, so it's like generating permutations for [a,b,c] where each of these elements is a 1d array of potentially varying length.
I'm sure the solution involves backtracking, but anytime I try to implement it I end up with a 5+ parameters. I was hoping one of you folks could kindly provide an elegant solution, pseudocode, or explanation.
You're really just permuting the row order, and then flattening the matrix for each permutation. Python example:
from itertools import chain, permutations
def flatten(matrix):
return list(chain(*matrix))
def permute(matrix):
return [flatten(perm) for perm in permutations(matrix)]
With your example:
>>> M = [[1], [5, 2], [6]]
>>> permute(M)
[[1, 5, 2, 6], [1, 6, 5, 2], [5, 2, 1, 6], [5, 2, 6, 1], [6, 1, 5, 2], [6, 5, 2, 1]]
In another language, you may have to implement your own helper functions to iterate through permutations (possibly using recursion), and list flattening.
In Java you can do it like the following(first get a permutation of all the indexes and then use that to generate the ans):
public class RowWisePermutation {
public static void main(String[] args) {
int[][] A = {
{1},
{5, 2},
{6}
};
generateRowWisePermutation(A);
}
public static List<List<Integer>> generateRowWisePermutation(int[][] matrix) {
List<Integer> temp = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
List<List<Integer>> indexPermutation = new ArrayList<>();
int[] indexArr = new int[matrix.length];
for(int i = 0; i < matrix.length; i++) {
indexArr[i] = i;
}
backtrack(indexArr, temp, indexPermutation);
System.out.println(indexPermutation);
for(int i = 0; i < indexPermutation.size(); i++) {
List<Integer> row = new ArrayList<>();
List<Integer> indices = indexPermutation.get(i);
for(Integer index : indices) {
for(int j = 0; j < matrix[index].length; j++) {
row.add(matrix[index][j]);
}
}
ans.add(row);
}
System.out.println(ans);
return ans;
}
private static void backtrack(int[] arr, List<Integer> temp,
List<List<Integer>> indexPermutation) {
if(temp.size() == arr.length) {
indexPermutation.add(new ArrayList<>(temp));
return;
}
for(int i = 0; i < arr.length; i++) {
if(temp.contains(i)) { continue; }
temp.add(arr[i]);
backtrack(arr, temp, indexPermutation);
temp.remove(temp.size() - 1);
}
}
}

Find all ways to partition a set into given-sized subsets

It isn't really complicated, but I just can't figure out how to do it.
I have one set with objects, let's say they are numbers. I need to check all the possibilities of N groups (we can assume there are 3 groups, 9 objects in set), where order inside group doesn't matter ({1,2,3}, {2,1,3}, {3,2,1}, etc. are the same) and order of groups doesn't matter ([{1,2,3},{4,5,6}] is the same as [{5,4,6},{2,1,3}]).
I'm writing code in C#, but there really isn't anything I could show. The closest idea I had contained a lot of fors and ifs 😞
The solution I've used places the elements in order; this avoids any problems of duplication. It uses recursion and backtracking to find all solutions.
The critical restriction to keep from duplicating a solution is that you may not place an element into the nth partition unless all lower-numbered partitions are non-empty.
Consider your problem, 9 students in 3 partitions. We start with three empty sets
{} {} {}
We now need to place students [1, 2, 3, 4, 5, 6, 7, 8, 9] into this partition set. Call our function
place({ {}, {}, {} }, [1, 2, 3, 4, 5, 6, 7, 8, 9])
We place the students in order. Student 1 has only one place to go: the first partition. Otherwise, we would violate the restriction.
place({ {1}, {}, {} }, [2, 3, 4, 5, 6, 7, 8, 9])
Student 2 can go into either of the first two partitions (i.e. you'll need an iteration loop to cover the legal possibilities). From here, you'll cycle through two recursive calls:
place({ {1, 2}, {}, {} }, [3, 4, 5, 6, 7, 8, 9])
place({ {1}, {2}, {} }, [3, 4, 5, 6, 7, 8, 9])
In the first call, 3 cannot yet go into the 3rd partition; in the second call, it can go anywhere.
Do you see how this works? As the partitions fill up (I infer a limit of 3 students in each group), you'll need to check for a full group, as well. At the end, each time you place the final student, you have a valid, unique arrangement.
Coding is left as an exercise for the reader. :-)
Well I wrote this yesterday. It takes a lot of time to generate all solutions, but it works. I suppose I can make it faster if I use some tree to store elements (now every new group is compared with all existing groups).
Edit: Actualy now when I think about it, I'm not sure if there are possible duplicats. I wrote that when I had for loop through all elements. Maybe I can remove that "if" to make it faster. I'll check that when I'll have access to my laptop.
There were no dups. Now it's fast and result seems to be okay.
public class Group<T> : IComparable<Group<int>>
{
public Group(IEnumerable<T> elements)
{
Elements = elements.OrderBy(n => n).ToArray();
}
public T[] Elements { get; }
public bool Equals(Group<T> other)
{
if (object.ReferenceEquals(this, other))
return true;
//assume number of elements in groups are equal
for (int i = 0; i < Elements.Length; i++)
if (!Elements[i].Equals(other.Elements[i]))
return false;
return true;
}
public int CompareTo(Group<int> other)
{
int[] elements = Elements as int[];
for (int i = 0; i < Elements.Length; i++)
{
if (elements[i] < other.Elements[i])
return -1;
else if (elements[i] > other.Elements[i])
return 1;
}
return 0;
}
public override string ToString()
{
string result = "{";
for (int i = 0; i < Elements.Length; i++)
result += Elements[i] + (i == Elements.Length - 1 ? "" : ", ");
result += "}";
return result;
}
}
class Program
{
static void Main(string[] args)
{
int[] allElements = {1, 2, 3, 4, 5, 6, 7, 8, 9};
List<Group<int>> singleGroupCombinations = new List<Group<int>>();
for (int i = 0; i < allElements.Length; i++)
{
for (int j = i + 1; j < allElements.Length; j++)
{
for (int k = j + 1; k < allElements.Length; k++)
{
Group<int> newGroup = new Group<int>(new[]
{
allElements[i], allElements[j], allElements[k]
});
singleGroupCombinations.Add(newGroup);
}
}
}
List<Group<Group<int>>> groupsCombinations = new List<Group<Group<int>>>();
for (int i = 0; i < singleGroupCombinations.Count; i++)
{
for (int j = i+1; j < singleGroupCombinations.Count; j++)
{
for (int k = j+1; k < singleGroupCombinations.Count; k++)
{
Group<Group<int>> newGroup = new Group<Group<int>>(new[]
{
singleGroupCombinations[i], singleGroupCombinations[j], singleGroupCombinations[k]
});
groupsCombinations.Add(newGroup);
}
}
}
//all groups combinations in groupCombinations variable
}
}

How do I account for duplicate values when solving the the two sum problem using a hash table?

Say I have the classic Two Sum Problem but with a twist
If I am given a list of integers and target
I need to print all the pairs of values that add up to the sum
Without repeating symmetrical values
Without reusing a value
I am trying to avoid the brute force approach for obvious reasons, but if I implement a hash-map with each value as the key and the element being the frequency of that value in the original array. How do I get the algorithm to only print each value pair once?
function findPairs(arr, target){
let hashMap = {};
let results = [];
for(let i = 0; i < arr.length; i++){
if(hashMap.hasOwnProperty(arr[i])){
hashMap[arr[i]]++;
}else{
hashMap[arr[i]] = 1;
}
}
for(let i = 0; i < arr.length; i++){
let diff = target - arr[i];
if(hashMap.hasOwnProperty(diff) && hashMap[diff] > 0){
results.push([arr[i], diff]);
hashMap[diff]--;
}
}
console.log(results);
}
findPairs([1, 3, -1, 11, 7], 10);
findPairs([5, 5, 5, 5, 5], 10);
findPairs([1, 3, -1, 11, 7], 10)
(3, 7)
(-1, 11)
findPairs([5, 5, 5], 10)
(5, 5)
findPairs([5, 5, 5, 5], 10)
(5, 5)
(5, 5)
findPairs([5, 5, 5, 5, 5], 10)
(5, 5)
(5, 5)
findPairs([5, 5, 5, 5, 5, 5 ], 10)
(5, 5)
(5, 5)
(5, 5)
This is the summary of the question as far as I understood:
Your array can have duplicate elements eg:- [1, 2, 3, 2, 4]
You want to print duplicate [4, 1, 2, 3, 2, 4] as (2, 4), (2, 4)
vector<pair<int, int> > findPairs(vector<int> arr, int target){
int size = arr.size();
map<int, int> hashMap;
for(int i = 0; i < size; i++){
// C++ map assigns 0 as default if the key is not present, C++ map uses Red Black Tree
if(hashMap[arr[i]] == 0)
hashMap[arr[i]] = 1;
else
hashMap[arr[i]]++;
}
/** Use to store result in (int, int) form
* Vector is a Dynamic array
*/
vector<pair<int, int> > results;
for(int i = 0; i < size; i++){
int diff = target - arr[i];
hashMap[arr[i]]--;
if(hashMap[diff] >= 1)
results.push_back(make_pair(arr[i], diff));
hashMap[diff]--;
}
return results;
}
This code is based on the examples you have provided in the question.

Sort an large array, keeping some elements in place (every language)

Can everybody help me? I have a problem: Given an array of array elements (Unlimited number of array elements). Sort the elements in ascending order, but keep any elements with the value -1 in the original position.
example: a=[4, -1, 5, 1, 8, 3, 2, -1]
after sort: a=[1, -1, 2, 3, 4, 5, 8, -1]
Here's how you might accomplish that in C#:
using System;
using System.Collections.Generic;
namespace NameSpace
{
class Class
{
static int[] a = { 4, -1, 5, 1, 8, 3, 2, -1 };
static List<int> Storage = new List<int>();
static int indexToAdd = 0;
static void Main()
{
foreach(int i in a)
{
if(i != -1)
{
Storage.Add(i);
}
}
Storage.Sort();
for(int i = 0; i < Storage.Count; i++)
{
if(a[indexToAdd + i] == -1)
{
indexToAdd++;
}
a[indexToAdd + i] = Storage[i];
}
foreach(int i in a)
{
Console.WriteLine(i);
}
Console.Read();
}
}
}
You can create a new list with the indices of every item that is not -1, i.e. the indices of the items that need sorting, then follow one of the examples in this RosettaCode Task: Sort disjoint sublist

Make 2D array into 1D array in Processing

I am trying to flatten a two dimensional array into a one dimensional array. This is what I currently have. I would like the flatten out my array so that the one dimensional array looks like this
int[] oneDim = {1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10, 11, 12};
This is what I currently have. I dont really know how to go about doing this. All help and input is appreciated.
void setup() {
int[][] twoDim = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} };
int[] oneDim = new int[twoDim.length];
for (int i = 0; i < twoDim.length; i++) {
for (int j = 0; j < twoDim[i].length; j++) {
oneDim[j] += twoDim[j][i];
}
}
println(oneDim);
}
int[][] twoDim = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} };
int x = twoDim.length;
int y = twoDim[0].length;
int[] oneDim = new int[x*y];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
oneDim[i*y + j] = twoDim[i][j];
}
}
println(oneDim);
Here's a hint: the usual formula for mapping two dimensions to one is: width*y + x, where width is the number of elements in each row (4, in your case, as given by twoDim[i].length, assuming they are all the same length), 'x' is the iterator over columns (j, in your case), and y is the iterator over rows (i for you).
You will want to check that the size of your one dimensional array is sufficient to accept all the elements of twoDim. It doesn't look big enough as it is - it needs to be twoDim[i].length * twoDim.length elements long, at least.
You're currently writing the same row of data over and over again, because you're assigning to oneDim[j] in the inner loop for every iteration of the outer loop. Try assigning to oneDim (once it is of appropriate size) using the formula I suggested at the start of this answer instead.

Resources