Subtraction between two lists - list

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(" | ");
}
}
}

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]

Problem: Shortest path in a grid between multiple point with a constraint

Problem description:
I'm trying to solve a problem on the internet and I wasn't able to pass all testcases, well, because my logic is flawed and incorrect. The flaw: I assumed starting to the closest 'F' point will get me to the shortest paths always, at all cases.
Thinks I thought of:
Turning this into a graph problem and solve it based on it. > don't think this would work because of the constraint?
Try to obtain all possible solution combinations > does not scale, if !8 combination exist.
#include <iostream>
#include <utility>
#include <string>
#include <vector>
#include <queue>
using namespace std;
#define N 4
#define M 4
int SearchingChallenge(string strArr[], int arrLength) {
int n = arrLength, m = n, steps = 0, food = 0;
// initial position of charlie
int init_j = 0;
int init_i = 0;
queue<pair<int,int>> q;
// directions
vector<int> offsets = {0,-1,0,1,0};
vector<pair<int,int>> food_nodes;
//store visited nodes, no need for extra work to be done.
int visited_nodes[4][4] = {{0}};
// get number of food pieces
for(int i = 0; i < m; i++){
for(int j = 0; j < n ; j++){
if(strArr[i][j] == 'F')
{
food++;
}
if(strArr[i][j] == 'C')
{
strArr[i][j] = 'O';
food_nodes.push_back({i,j});
}
}
}
while(food_nodes.size()>0){
food_nodes.erase(food_nodes.begin());
int break_flag=0;
q.push(food_nodes[0]);
while(!q.empty()){
int size = q.size();
while(size-->0){
pair<int,int> p = q.front();
q.pop();
for(int k = 0; k < 4; k++){
int ii = p.first + offsets[k], jj = p.second + offsets[k+1];
/* if(ii == 0 && jj == 3)
printf("HI"); */
if(jj >= 0 && jj < 4 && ii < 4 && ii >=0){
if(strArr[ii][jj] == 'F'){
strArr[ii][jj] = 'O';
while(!q.empty())
q.pop();
break_flag=1;
food--;
food_nodes.push_back({ii,jj});
break;
}
if(strArr[ii][jj] == 'O')
q.push({ii,jj});
if(strArr[ii][jj] == 'H' && food == 0)
return ++steps;
}
}
if(break_flag==1)
break;
}
steps++;
if(break_flag==1)
break;
}
}
return 0;
}
int main(void) {
// keep this function call here
/* Note: In C++ you first have to initialize an array and set
it equal to the stdin to test your code with arrays. */
//passing testcase
//string A[4] = {"OOOO", "OOFF", "OCHO", "OFOO"};
//failing testcase
string A[4] = {"FOOF", "OCOO", "OOOH", "FOOO"}
int arrLength = sizeof(A) / sizeof(*A);
cout << SearchingChallenge(A, arrLength);
return 0;
}
Your help is appreciated.
I have wrote the javascript solution for the mentioned problem..
function SearchingChallenge(strArr) {
// create coordinate array
const matrix = [
[0, 0], [0, 1], [0, 2], [0, 3],
[1, 0], [1, 1], [1, 2], [1, 3],
[2, 0], [2, 1], [2, 2], [2, 3],
[3, 0], [3, 1], [3, 2], [3, 3]
]
// flatten the strArr
const flattenArray = flatten(strArr)
// segreagate and map flattenArray with matrix to get coordinate of food,charlie and home
const segregatedCoordinates = flattenArray.reduce((obj, char, index) => {
if (char === 'F') obj['food'].push(matrix[index])
else if (char === 'C') obj['dog'] = matrix[index]
else if (char === 'H') obj['home'] = matrix[index]
return obj
}, { "food": [], dog: null, home: null })
// construct possible routes by permutating food coordinates
let possibleRoutes = permuate(segregatedCoordinates['food'])
// push dog and home in possibleRoutes at start and end positions
possibleRoutes = possibleRoutes.map((route) => {
return [segregatedCoordinates['dog'], ...route, segregatedCoordinates['home']]
})
// Calculate distances from every possible route
const distances = possibleRoutes.reduce((distances, route) => {
let moveLength = 0
for (let i = 0; i < route.length - 1; i++) {
let current = route[i], next = route[i + 1]
let xCoordinatePath = current[0] > next[0] ? (current[0] - next[0]) : (next[0] - current[0])
let yCoordinatePath = current[1] > next[1] ? (current[1] - next[1]) : (next[1] - current[1])
moveLength += xCoordinatePath + yCoordinatePath
}
distances.push(moveLength)
return distances
}, [])
return Math.min(...distances);
}
function permuate(arr) {
if (arr.length <= 2) return (arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr)
return arr.reduce((res, ele, index) => {
res = [...res, ...permuate([...arr.slice(0, index), ...arr.slice(index + 1)]).map(val => [ele, ...val])]
return res
}, [])
}
function flatten(inputtedArr) {
return inputtedArr.reduce((arr, row) => {
arr = [...arr, ...row]
return arr
}, [])
}
console.log(SearchingChallenge(['FOOF', 'OCOO', 'OOOH', 'FOOO']));
You can write a DP solution where you have a 4x4x8 grid. The first two axis represent the x and y coordinate. The third one represent the binary encoding of which food item you picked already.
Each cell in the grid stores the best number of moves to get at this cell having eaten the specified foods. So for example, grid[2][2][2] is the cost of getting to cell (2,2) after having eaten the second piece of food only.
Then you set the value of the start cell, at third index 0 to 0, all the other cells to -1. You keep a list of the cells to propagate (sorted by least cost), and you add the start cell to it.
Then you repeatedly take the next cell to propagate, remove it and push the neighboring cell with cost +1 and updated food consume. Once you reach the destination cell with all food consumed, you're done.
That should take no more than 4x4x8 updates, with about the same order of priority queue insertion. O(n log(n)) where n is xy2^f. As long as you have few food items this will be almost instant.
C++ solution
I used both dfs and bfs for this problem
TIME COMPLEXITY - (4^(N×M))+NO_OF_FOODS×N×M
#include <bits/stdc++.h>
using namespace std;
//It is a dfs function it will find and store all the possible steps to eat all food in toHome map
void distAfterEatingAllFood(vector<vector<char>> &m, int countOfFood, int i, int j, int steps, map<pair<int,int>,int>&toHome){
if(i<0 || j<0 || i>=4 || j>=4 || m[i][j]=='*') return;
if(m[i][j]=='F') countOfFood--;
if(countOfFood==0){
if(!toHome.count({i,j}))
toHome[{i,j}] = steps;
else if(toHome[{i,j}]>steps)
toHome[{i,j}] = steps;
return;
}
char temp = m[i][j];
m[i][j] = '*';
distAfterEatingAllFood(m, countOfFood, i+1, j, steps+1, toHome);
distAfterEatingAllFood(m, countOfFood, i-1, j, steps+1, toHome);
distAfterEatingAllFood(m, countOfFood, i, j+1, steps+1, toHome);
distAfterEatingAllFood(m, countOfFood, i, j-1, steps+1, toHome);
m[i][j] = temp;
return;
}
//It is a bfs function it will iterate over the toHome map and find the shortest distance between the last food position to home
int lastFoodToHome(vector<vector<char>> &m, int i, int j, int steps){
queue<pair<pair<int, int>,int>>q;
vector<vector<int>> vis(4, vector<int>(4, 0));
q.push({{i, j}, steps});
vis[i][j] = 1;
int dirX[] = {0, 1, 0, -1};
int dirY[] = {1, 0, -1, 0};
while (!q.empty())
{
int x = q.front().first.first;
int y = q.front().first.second;
int steps = q.front().second;
q.pop();
if (m[x][y] == 'H')
return steps;
for (int k = 0; k < 4; k++)
{
int ni = x + dirX[k];
int nj = y + dirY[k];
if (ni >= 0 && nj >= 0 && ni < 4 && nj < 4 && !vis[ni][nj])
{
if(m[ni][nj] == 'H') return steps + 1;
q.push({{ni, nj}, steps + 1});
vis[i][j] = 1;
}
}
}
return INT_MAX;
}
int main()
{
vector<vector<char>> m(4, vector<char>(4));
int countOfFood = 0, x, y;
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
cin >> m[i][j];
if (m[i][j] == 'C'){
x = i;
y = j;
}
if (m[i][j] == 'F')
countOfFood++;
}
}
map<pair<int,int>,int>toHome;
distAfterEatingAllFood(m, countOfFood, x, y, 0, toHome);
int ans = INT_MAX;
for(auto &i:toHome){
ans = min(ans, lastFoodToHome(m, i.first.first, i.first.second, i.second));
}
cout<<ans;
return 0;
}

Random to Multi-List Number from One 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;
}

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++;
}

C++ Chocolate Puzzle [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Let's say I have N chocolates that have to be packed into exactly P boxes in the order they arrive. Each chocolate also has a number of calories X and each box has a capacity K which has to be less than or equal to 3*sum(x1, x2, ..., xn) + max(x1, x2, ..., xn)^2 - min(x1, x2, ..., xn)^2.
In the task I'm given N, P and X for each chocolate and I have to figure out the lowest possible K. Could anyone help me on this (not looking for a solution just for some hints regarding the problem)?
Example:
N = 8,
P = 3,
X = {1, 4, 5, 6, 3, 2, 5, 3}
K for first three chocolates = 3*(1+4+5) + 5^2 - 1^2 = 54
K for next two chocolates = 3*(6+3) + 6^2 - 3^2 = 54
K for last three chocolates = 3*(2+5+3) + 5^2 - 2^2 = 51
Lowest possible K = 54
So the goal is to find the best combination using exactly P boxes that has the lowest K.
Thanks!
Here is how I would solve this in Java:
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ChocolatePuzzle {
private static final Map <String, Integer> solutions =
new HashMap <String, Integer> ();
private static final Map <String, Integer> bestMoves =
new HashMap <String, Integer> ();
private static int [] x;
private static int k (int from, int to)
{
int sum = x [from];
int max = x [from];
int min = x [from];
for (int i = from + 1; i < to; i++)
{
sum += x [i];
max = Math.max (max, x [i]);
min = Math.min (min, x [i]);
}
return sum * 3 + max * max - min * min;
}
public static int solve (int n, int p)
{
String signature = n + "," + p;
Integer solution = solutions.get (signature);
if (solution == null)
{
solution = Integer.valueOf (doSolve (n, p, signature));
solutions.put (signature, solution);
}
return solution.intValue ();
}
public static int doSolve (int n, int p, String signature)
{
if (p == 1)
{
bestMoves.put (signature, Integer.valueOf (x.length - n));
return k (n, x.length);
}
else
{
int result = Integer.MAX_VALUE;
int bestMove = 0;
int maxI = x.length - n - p + 1;
for (int i = 1; i <= maxI; i++)
{
int k = Math.max (k (n, n + i), solve (n + i, p - 1));
if (k < result)
{
result = k;
bestMove = i;
}
}
bestMoves.put (signature, Integer.valueOf (bestMove));
return result;
}
}
public static void main(String[] args) {
int n = 20;
int p = 5;
x = new int [n];
Random r = new Random ();
for (int i = 0; i < n; i++)
x [i] = r.nextInt (9) + 1;
System.out.println("N: " + n);
System.out.println("P: " + p);
System.out.print("X: {");
for (int i = 0; i < n; i++)
{
if (i > 0) System.out.print (", ");
System.out.print (x [i]);
}
System.out.println("}");
System.out.println();
int k = solve (0, p);
int o = 0;
for (int i = p; i > 0; i--)
{
int m = bestMoves.get (o + "," + i);
System.out.print ("{");
for (int j = 0; j < m; j++)
{
if (j > 0)
System.out.print (", ");
System.out.print (x [o + j]);
}
System.out.print ("} (k: ");
System.out.print(k (o, o + m));
System.out.println (")");
o += m;
}
System.out.println("min(k): " + k);
}
}
Probably you could find some useful tips in this code.
Sample input:
N: 20
P: 5
X: {1, 7, 6, 6, 5, 5, 7, 9, 1, 3, 9, 5, 3, 7, 9, 1, 4, 2, 4, 8}
Sample output:
{1, 7, 6, 6} (k: 108)
{5, 5, 7, 9} (k: 134)
{1, 3, 9, 5} (k: 134)
{3, 7, 9} (k: 129)
{1, 4, 2, 4, 8} (k: 120)
min(k): 134