Random to Multi-List Number from One List - list

I have an array:
int arr[] = {1, 2, 3, 4}
How can I randomize arr[] to multi-list with No Duplicates?
FROM
arr[] = { 1, 2, 3, 4 }
TO
arr1[] = {1, 2, 3, 4}
arr2[] = {2, 1, 4, 3}
arr3[] = {3, 4, 1, 2}
arr4[] = {4, 3, 2, 1}

In this case, it is preferable to use a List<Integer> instead of int[]
List<Integer> arr = new ArrayList<Integer>();
Random random = new Random();
int randonint = arr.remove(random.nextint(arr.getSize()));
Every time this code is runned, it will grab a random int from the list arr, then you can add it to a different List/Array
So, if you want to take all values from one list, and randomly place them to 3 other lists, use the following code:
List<Integer> arr1 = new ArrayList<Integer>();
List<Integer> to1 = new ArrayList<Integer>();
List<Integer> to2 = new ArrayList<Integer>();
List<Integer> to3 = new ArrayList<Integer>();
Random random = new Random();
for (int i = 1 ; i <= 10 ; i++) {
arr1.add(i);
}
for (int count = 0 ; count < arr1.size() ; count++) {
List<Integer> arr = new ArrayList<Integer>();
int randomvalue = arr.remove(random.nextint(arr.getSize()));
switch (random.nextInt(3)) {
case 0:
to1.add(randomvalue);
case 1:
to2.add(randomvalue);
case 2:
to2.add(randomvalue);
}
}

public static void GenerateRandomArray()
{
var inputArray = new[] {1, 2, 3, 4};
var outputArray = GetRandomArray(inputArray);
PrintArray(outputArray);
}
private static void PrintArray(int[,] outputArray)
{
for (var i = 0; i < outputArray.GetLength(0); i += 1)
{
for (var j = 0; j < outputArray.GetLength(1); j += 1)
{
Console.Write(outputArray[i, j]);
}
Console.WriteLine();
}
}
private static int[,] GetRandomArray(int[] inputArray)
{
var lengthOfArray = inputArray.Length;
var outputArray = new int[lengthOfArray,lengthOfArray];
for (var i = 0; i < lengthOfArray; i++)
{
var counterShifter = i;
for (var j = 0; j < lengthOfArray;j++)
{
outputArray[i, j] = inputArray[counterShifter];
counterShifter = counterShifter + 1 < lengthOfArray
? counterShifter + 1 :
0;
}
}
return outputArray;
}

Related

How do I multiply two lists in flutter

How do I multiply two distinct lists in flutter. Like example below
List a = [2,3];
List b = [1,4];
List c = [3,5];
how do I obtain
List d = [6,60];
void main() {
List a = [2, 3];
List b = [1, 4];
List c = [3, 5];
List d = [];
for (int i = 0; i < a.length; i++) {
d.add(a[i] * b[i] * c[i]);
}
print(d);
}
if you do not know:
amount of lists you receive
amount of elements in the lists
You can do something like:
void main() {
//creating an empty growable list of list
List<List<int>> listOfLists = List.generate(0, (i) => []);
//your N List, maybe from api or something
List<int> a = [2, 3];
List<int> b = [1, 4];
List<int> c = [3, 5];
//adding all list to main one
listOfLists.addAll([a, b, c]);
//creating list which will have results
final results = [];
//recursive logic
listOfLists.asMap().forEach((listOfListsIndex, list) {
if (listOfListsIndex == 0) {
//adding first values as there's none to multiply
//you can remove the if statement if you init earlier
//final results = listOfLists[0];
//listOfLists.removeAt(0);
results.addAll(list);
} else {
list.asMap().forEach((listIndex, value) {
if (results.length > listIndex) {
//case when listOfLists[0] length is minor
//preventing error
//List<int> a = [2];
//List<int> b = [1, 4];
//List<int> c = [3, 5];
//List<int> d = [3, 5, 4, 6, 7];
results[listIndex] = results[listIndex] * value;
} else {
results.add(value);
}
});
}
});
print(results);
//[6, 60]
}
Generalized function to do this, where input is a List of a List of integers, where the lengths of each list can be anything.
List<int> productList(List<List<int>> input) {
// handle some edge cases
if (input.isEmpty) {
return [];
} else if (input.length < 2) {
return input.first;
}
// sort the input so the largest list is first
input.sort(
(listA, listB) => listB.length.compareTo(listA.length),
);
var product = input.first;
for (var productIndex = 0; productIndex < product.length; productIndex++) {
// iterate over the rest of the list, keep multiplying if each list
// contains a number at productIndex
for (var inputIndex = 1; inputIndex < input.length; inputIndex++) {
var numList = input[inputIndex];
if (numList.length > productIndex) {
product[productIndex] *= numList[productIndex];
} else {
break;
}
}
}
return product;
}
In your example:
var a = [2,3];
var b = [1,4];
var c = [3,5];
var input = [a, b, c];
print(productList(input));
yields:
[6, 60]

Algorithms - Circular Array Rotation

Is this linear complexity implementation of circular array rotation correct?
n = number of elements
k = number of rotations
int write_to = 0;
int copy_current = 0;
int copy_final = a[0];
int rotation = k;
int position = 0;
for (int i = 0; i < n; i++) {
write_to = (position + rotation) % n;
copy_current = a[write_to];
a[write_to] = copy_final;
position = write_to;
copy_final = copy_current;
}
No.
Consider this example.
#include <iostream>
int main(void) {
int n = 6;
int k = 2;
int a[] = {1, 2, 3, 4, 5, 6};
int write_to = 0;
int copy_current = 0;
int copy_final = a[0];
int rotation = k;
int position = 0;
for (int i = 0; i < n; i++) {
write_to = (position + rotation) % n;
copy_current = a[write_to];
a[write_to] = copy_final;
position = write_to;
copy_final = copy_current;
}
for (int i = 0; i < n; i++) {
std::cout << a[i] << (i + 1 < n ? ' ' : '\n');
}
return 0;
}
Expected result:
5 6 1 2 3 4
Actual result:
3 2 1 4 1 6
Using stl::rotate on std::array, you can left rotate by, say 2, as:
std::array<int, 6> a{1, 2, 3, 4, 5, 6};
std::rotate(begin(a), begin(a) + 2, end(a)); // left rotate by 2
to yield: 3 4 5 6 1 2, or right-rotate by, say 2, as:
std::rotate(begin(a), end(a) - 2, end(a)); // right rotate by 2
to yield: 5 6 1 2 3 4, with linear complexity.
Rotate an Array of length n for k times in left or right directions.
The code is in Java
I define a Direction Enum:
public enum Direction {
L, R
};
Rotation with times and direction:
public static final void rotate(int[] arr, int times, Direction direction) {
if (arr == null || times < 0) {
throw new IllegalArgumentException("The array must be non-null and the order must be non-negative");
}
int offset = arr.length - times % arr.length;
if (offset > 0) {
int[] copy = arr.clone();
for (int i = 0; i < arr.length; ++i) {
int j = (i + offset) % arr.length;
if (Direction.R.equals(direction)) {
arr[i] = copy[j];
} else {
arr[j] = copy[i];
}
}
}
}
Complexity: O(n).
Example:
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Rotate 3 times left
Output: [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
Input: [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
Rotate 3 times right
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

C++ Store latest values from a large array in a separate array

I need a way to store the latest 3 values of a large array into a separate array, but can't for the life in me figure out how to code it.
It's something in this direction:
int w[3] = {0, 0, 0};
int x[12] = {0, 2, 4, 6, 4, 2, 0, 2, 4, 6, 4, 2};
w[0] = x[i];
w[1] = x[i-1];
w[2] = x[i-2];
So if i = 2 , then:
w[0] = x[2] = 4
w[1] = x[2-1] = 2
w[2] = x[2-2] = 0
The point is to use it in a code like this:
for (i=0; i<200; i++){
//store x[i], x[i-1] and x[i-2] into 'w' for every value 'i'
//compensate for undefined 'x'-values (such as x[0-1] and x[0-2] )
//by writing '0' to corresponding 'w'
}
Update according to:
w[2] = w[1];
w[1] = w[0];
w[0] = x[i];
w[0] = 0;
w[1] = 0;
w[2] = 0;
w[0] = x[i];
if (i>=1)
{
w[1] = x[i-1] ;
}
if ( i>= 2)
{
w[2] = x[i-2];
}
Assuming you know the size of your large array is 200-
s = 0;
for (l = 200 ; l > 197 ; l--) {
x[s] = w[l];
s++;
}

Subtraction between two lists

Suppose I have two lists:
x = [[1,2,3],[5,4,20],[9,100,7]]
y = [[1,1,1],[1,1,1],[1,1,1]]
I am trying to get z = x - y so that my array should be like
z = [[0, 1, 2], [4, 3, 19], [8, 99, 6]]
For example in Java
public class Main {
public static void main(String[] args) {
int[][] x = new int[][]{
{1,2,3},
{5,4,20},
{9,100,7}
};
int[][] y = new int[][]{
{1,1,1},
{1,1,1},
{1,1,1}
};
int[][] result = new int[3][3];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
result[i][j] = x[i][j] - y[i][j];
System.out.print(result[i][j]+ " ");
}
System.out.print(" | ");
}
}
}

fastest algorithm count number of 3 length AP in array

I want to solve this CodeChef challenge:
Suppose We are given an array A of N(of range 100,000) elements. We are to find the count of all pairs of 3 such elements 1<=Ai,Aj,Ak<=30,000 such that
Aj-Ai = Ak- Aj and i < j < k
In other words Ai,Aj,Ak are in Arithmetic Progression. For instance for Array :
9 4 2 3 6 10 3 3 10
so The AP are:
{2,6,10},{9,6,3},{9,6,3},{3,3,3},{2,6,10}
So the required answer is 5.
My Approach
What I tried is take 30,000 long arrays named past and right. Initially right contains the count of each 1-30,000 element.
If we are at ith position past stores the count of array value before i and right stores the count of array after i. I simply loop for all possible common difference in the array. Here is the code :
right[arr[1]]--;
for(i=2;i<=n-1;i++)
{
past[arr[i-1]]++;
right[arr[i]]--;
k=30000 - arr[i];
if(arr[i] <= 15000)
k=arr[i];
for(d=1;d<=k;d++)
{
ans+= right[arr[i] + d]*past[arr[i]-d] + past[arr[i] + d]*right[arr[i]-d];
}
ans+=past[arr[i]]*right[arr[i]];
}
But this gets me Time Limit Exceeded. Please help with a better algorithm.
You can greatly cut execution time if you make a first pass over the list and only extract number pairs that it is possible to have an 3 term AP between (difference is 0 mod 2). And then iterating between such pairs.
Pseudo C++-y code:
// Contains information about each beginning point
struct BeginNode {
int value;
size_t offset;
SortedList<EndNode> ends; //sorted by EndNode.value
};
// Contains information about each class of end point
struct EndNode {
int value;
List<size_t> offsets; // will be sorted without effort due to how we collect offsets
};
struct Result {
size_t begin;
size_t middle;
size_t end;
};
SortedList<BeginNode> nodeList;
foreach (auto i : baseList) {
BeginNode begin;
node.value = i;
node.offset = i's offset; //you'll need to use old school for (i=0;etc;i++) with this
// baseList is the list between begin and end-2 (inclusive)
foreach (auto j : restList) {
// restList is the list between iterator i+2 and end (inclusive)
// we do not need to consider i+1, because not enough space for AP
if ((i-j)%2 == 0) { //if it's possible to have a 3 term AP between these two nodes
size_t listOffset = binarySearch(begin.ends);
if (listOffset is valid) {
begin.ends[listOffset].offsets.push_back(offsets);
} else {
EndNode end;
end.value = j;
end.offsets.push_back(j's offset);
begin.ends.sorted_insert(end);
}
}
}
if (begin has shit in it) {
nodeList.sorted_insert(begin);
}
}
// Collection done, now iterate over collection
List<Result> res;
foreach (auto node : nodeList) {
foreach (auto endNode : node.ends) {
foreach (value : sublist from node.offset until endNode.offsets.last()) {
if (value == average(node.value, endNode.value)) {
// binary_search here to determine how many offsets in "endNode.offsets" "value's offset" is less than.
do this that many times:
res.push_back({node.value, value, endNode.value});
}
}
}
}
return res;
Here's a simple C version of the solution that takes advantage of the Ai + Ak must be even test:
#include <stdio.h>
static int arr[] = {9, 4, 2, 3, 6, 10, 3, 3, 10};
int main ()
{
int i, j, k;
int sz = sizeof(arr)/sizeof(arr[0]);
int count = 0;
for (i = 0; i < sz - 2; i++)
{
for (k = i + 2; k < sz; k++)
{
int ik = arr[i] + arr[k];
int ikdb2 = ik / 2;
if ((ikdb2 * 2) == ik) // if ik is even
{
for (j = i + 1; j < k; j++)
{
if (arr[j] == ikdb2)
{
count += 1;
printf("{%d, %d, %d}\n", arr[i], arr[j], arr[k]);
}
}
}
}
}
printf("Count is: %d\n", count);
}
and the console dribble:
tmp e$ cc -o triples triples.c
tmp e$ ./triples
{9, 6, 3}
{9, 6, 3}
{2, 6, 10}
{2, 6, 10}
{3, 3, 3}
Count is: 5
tmp e$
This more complicated version keeps a list of Aj indexed by value to go from n-cubed to n-squared (kinda).
#include <stdio.h>
#include <stdint.h>
static uint32_t arr[] = {9, 4, 2, 3, 6, 10, 3, 3, 10};
#define MAX_VALUE 100000u
#define MAX_ASIZE 30000u
static uint16_t index[MAX_VALUE+1];
static uint16_t list[MAX_ASIZE+1];
static inline void remove_from_index (int subscript)
{
list[subscript] = 0u; // it is guaranteed to be the last element
uint32_t value = arr[subscript];
if (value <= MAX_VALUE && subscript == index[value])
{
index[value] = 0u; // list now empty
}
}
static inline void add_to_index (int subscript)
{
uint32_t value = arr[subscript];
if (value <= MAX_VALUE)
{
list[subscript] = index[value]; // cons
index[value] = subscript;
}
}
int main ()
{
int i, k;
int sz = sizeof(arr)/sizeof(arr[0]);
int count = 0;
for (i = 0; i < sz - 2; i++)
{
for (k = i; k < sz; k++) remove_from_index(k);
for (k = i + 2; k < sz; k++)
{
uint32_t ik = arr[i] + arr[k];
uint32_t ikdb2 = ik / 2;
add_to_index(k-1); // A(k-1) is now a legal middle value
if ((ikdb2 * 2) == ik) // if ik is even
{
uint16_t rover = index[ikdb2];
while (rover != 0u)
{
count += 1;
printf("{%d, %d, %d}\n", arr[i], arr[rover], arr[k]);
rover = list[rover];
}
}
}
}
printf("Count is: %d\n", count);
}
and the dribble:
tmp e$ cc -o triples triples.c
tmp e$ ./triples
{9, 6, 3}
{9, 6, 3}
{2, 6, 10}
{2, 6, 10}
{3, 3, 3}
Count is: 5
tmp e$