Sodoku solver with arrays of bitsets

I wrote a quick sodoku solver as an exercise and am curious how to make it faster. Parsing and printing is largely irrelevant only there for readability. How can I make the code cleaner and faster?

#include <array> #include <tuple> #include <bitset> #include <cassert> #include <optional> #include <iostream>  constexpr std::size_t blocks_per_side = 3; constexpr std::size_t numbers = blocks_per_side * blocks_per_side; using Value = std::bitset<numbers>; using Row = std::array<Value, numbers>; using Grid = std::array<Row, numbers>; using NiceRow = std::array<std::size_t, numbers>; using NiceGrid = std::array<NiceRow, numbers>;  namespace MapArrayDetail { template <std::size_t index, typename Callable, typename... Args> constexpr auto MapIndex(const Callable& cal, const Args&... args) {     return cal(std::get<index>(args)...); }  template <typename OutType, std::size_t size, typename Callable,     std::size_t... Is, typename... Arrays> constexpr std::array<OutType, size> MapWithIndex(     const Callable& cal, std::index_sequence<Is...>, const Arrays&... arrays) {     return {MapIndex<Is>(cal, arrays...)...}; } }  template <typename Callable, typename... Arrays> constexpr auto Map(const Callable& cal, const Arrays&... arrays) {     using OutType =         std::invoke_result_t<decltype(cal), typename Arrays::value_type...>;     constexpr auto size =         std::get<0>(std::make_tuple(std::tuple_size_v<Arrays>...));     return MapArrayDetail::MapWithIndex<OutType, size>(         cal, std::make_index_sequence<size>(), arrays...); }  constexpr Value DeSerialize(std::size_t s) {     Value v{};     if (s != 0) {         v.set(s - 1);     }     return v; }  std::size_t Serialize(Value s) {     assert(s.count() <= 1);     for (std::size_t v = 0; v < numbers; v++) {         if (s[v]) {             return v + 1;         }     }     return 0; }  constexpr Grid DeSerialize(NiceGrid nice) {     return Map(         [](const auto& r) constexpr {             return Map([](const auto& v) constexpr { return DeSerialize(v); },                 r);         },         nice); }  NiceGrid Serialize(Grid g) {     return Map(         [](const auto& r) -> NiceRow {             return Map([](const auto& v) { return Serialize(v); }, r);         },         g); }  void print(NiceGrid g) {     for (std::size_t row = 0; row < numbers; row++) {         for (std::size_t col = 0; col < numbers; col++) {             std::cout << g[row][col] << ",";         }         std::cout << std::endl;     }     std::cout << std::endl; }  constexpr Row GetRow(const Grid& grid, std::size_t i) { return grid.at(i); }  template <std::size_t... indexes> constexpr Row GetColImpl(     const Grid& grid, std::size_t i, std::index_sequence<indexes...>) {     return {grid[indexes][i]...}; }  constexpr Row GetCol(const Grid& grid, std::size_t i) {     return GetColImpl(grid, i, std::make_index_sequence<numbers>()); }  template <std::size_t i> using ValFromIndex = Value;  template <std::size_t... indexes> constexpr std::tuple<ValFromIndex<indexes>...> GetBlockCol(const Grid& grid,     std::size_t row, std::size_t top_col, std::index_sequence<indexes...>) {     return {grid.at(row).at(top_col + indexes)...}; }  template <std::size_t... indexes> constexpr Row GetBlockImpl(const Grid& grid, std::size_t row, std::size_t col,     std::index_sequence<indexes...>) {     constexpr auto seq = std::index_sequence<indexes...>{};     const auto top_row = (row / blocks_per_side) * blocks_per_side;     const auto top_col = (col / blocks_per_side) * blocks_per_side;     return std::apply([](const auto&... v) { return Row{v...}; },         std::tuple_cat(GetBlockCol(grid, top_row + indexes, top_col, seq)...)); }  constexpr Row GetBlock(const Grid& grid, std::size_t row, std::size_t col) {     return GetBlockImpl(         grid, row, col, std::make_index_sequence<blocks_per_side>()); }  Value GetRemaining(const Grid& grid, std::size_t row_ind, std::size_t col_ind) {     Value v{};     constexpr auto or_op = [](const auto&... a) { return (a | ...); };     const auto ored = Map(or_op, GetCol(grid, col_ind), GetRow(grid, row_ind),         GetBlock(grid, row_ind, col_ind));     for (const auto& c : ored) {         v = v | c;     }     return ~v; }  using StartStop = std::tuple<std::size_t, std::size_t, Value>; constexpr StartStop start{numbers + 1, numbers + 1, {}}; StartStop GetMinPos(const Grid& grid) {     auto count = 2 * numbers;     StartStop row_col = start;     for (std::size_t row = 0; row < numbers; row++) {         for (std::size_t col = 0; col < numbers; col++) {             if (grid[row][col].none()) {                 auto r = GetRemaining(grid, row, col);                 const auto rcount = r.count();                 if (rcount < count) {                     count = rcount;                     row_col = {row, col, r};                 }             }         }     }     return row_col; }  bool Done(const Grid& g) {     constexpr auto row_has_zero = [](const Row& r) {         return std::find_if(r.begin(), r.end(),                    [](const auto& a) { return a.none(); }) != r.end();     };     return std::find_if(g.begin(), g.end(), row_has_zero) == g.end(); }  std::optional<Grid> BruteForce(const Grid& g) {     if (Done(g)) {         return g;     }     const auto[row, col, val] = GetMinPos(g);     if ((row > numbers) | val.none()) {         return std::nullopt;     }     for (std::size_t i = 0; i < numbers; i++) {         if (val[i]) {             auto g2 = g;             assert(g2[row][col].count() == 0);             g2[row][col].set(i);             auto res = BruteForce(g2);             if (res) {                 return res;             }         }     }     return std::nullopt; }  constexpr NiceGrid ex1_nice{ NiceRow{4, 0, 3, 0, 0, 0, 7, 1, 0},     {0, 0, 0, 0, 0, 0, 0, 0, 9},      {7, 0, 0, 0, 1, 9, 3, 4, 8},     {0, 0, 0, 7, 4, 0, 0, 0, 3},      {0, 0, 4, 0, 0, 0, 1, 0, 0},     {8, 0, 0, 0, 2, 3, 0, 0, 0},      {1, 6, 7, 3, 9, 0, 0, 0, 2},     {3, 0, 0, 0, 0, 0, 0, 0, 0},      {0, 5, 2, 0, 0, 0, 6, 0, 1}};  const Grid ex1 = DeSerialize(ex1_nice);  int main(int argc, char** argv) {     auto z = BruteForce(ex1);     if (!z) {         std::cout << "Failed" << std::endl;     }     print(Serialize(*z)); } 

Cleaning words from numpy arrays

I’m a new joiner in a software engineering team and have been given this code for refactoring. This code feels very gluey and dependent to me but I can’t decide how to make it independent.

This is the code. The part which takes long time to execute is

if order_counter is not None:     batch_inp = [(freq_cleaning_list[i:i+100000], \                   order_counter_cutoff, word_counter_cutoff)                  for i in range(0, len(freq_cleaning_list), 100000)] else:     batch_inp = [(freq_cleaning_list[i:i+100000], \                   word_counter_cutoff)                  for i in range(0, len(freq_cleaning_list), 100000)] 

cleaning_pipeline class contains the code. I would be thankful to get some initial pointers to get started with this refactor. Thanks

Parse complex XML with arrays in Java

I have a complex xml structure which I receive from 3rd party.I want to parse above xml document & create a Map with the respective values. Which library can be used to parse complex xml’s

I tried XPath however i was unable to get desired result

AA BB CC DD EE FF 10 20 30 40 50 60

I want to parse above xml document & create a Map with the respective values i.e. AA –>10, BB–>20 and so on. How do i achieve this in JAVA.

LeetCode: Intersection of two arrays ii C#

https://leetcode.com/problems/intersection-of-two-arrays-ii/

Please review for performance, I am having a problem with using TryGetValue, if someone can explain how this can be used in here.

Given two arrays, write a function to compute their intersection.

Example 1:  Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2:  Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: 

Each element in the result should appear as many times as it shows in both arrays. The result can be in any order.

using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting;  namespace ArrayQuestions {     /// <summary>     /// https://leetcode.com/problems/intersection-of-two-arrays-ii/     /// </summary>     [TestClass]     public class IntersectionOfTwoArraysii     {         [TestMethod]         public void IntersectionOfDouble2Test()         {             int[] nums1 = {1, 2, 2, 1};             int[] nums2 = {2, 2};             CollectionAssert.AreEqual(nums2, Intersect(nums1,nums2));         }          public int[] Intersect(int[] nums1, int[] nums2)         {             if (nums1.Length > nums2.Length)             {                 return Intersect(nums2, nums1);             }             Dictionary<int, int> nums1Count = new Dictionary<int, int>();             List<int> res = new List<int>();             foreach (var num in nums1)             {                 if (!nums1Count.ContainsKey(num))                 {                     nums1Count.Add(num,1);                 }                 else                 {                     nums1Count[num]++;                 }             }              foreach (var num in nums2)             {                 if (nums1Count.ContainsKey(num) && nums1Count[num] > 0)                 {                     res.Add(num);                     nums1Count[num]--;                 }             }              return res.ToArray();         }     } } 

JavaScript concurrency in updating arrays

This is probably a vary noob question, but I cannot figure out what is happening. I have a simple function that I run:

function f() {   var x = [{a:1, b: 2}, {a: 3, b: 4}];   console.log(x);   x.push({a: 5, b: 6});   console.log(x); f(); 

The two console.log outputs show the same thing with all three elements which I cannot understand. If I change function so that the array only contains numbers:

function f() {   var x = [1, 2];   console.log(x);   x.push(3);   console.log(x); f(); 

then the outputs looks as I would have expected with the first one showing a list with items 1,2 and the second showing a list with 1,2,3.

This all runs in Firefox.

Displays data arrays with appendrow where other columns contain data

I wrote a script to display a list of names and folder IDs.

The script that I wrote like this:

function listFolders() {  var sheet = SpreadsheetApp.getActiveSheet();   sheet.getRange('A2:B').clear();   //sheet.appendRow(["Name", "Folder-Id"]);  var folderID = DriveApp.getFolderById("1Hp_dM8WR0mGDT5q-a-VS-VVtl5dNCLfe"); var contents = folderID.getFolders();  var cnt = 0; var lFolder;  while (contents.hasNext()) {     var lFolder = contents.next();     cnt++;         data = [             lFolder.getName(),             lFolder.getId(),         ];           sheet.appendRow(data);     }; }; 

I want to add new data in column C. After I fill in a text in column C, then I run the script. But the second row is empty.

enter image description here

Comparar dos arrays con array_intersect

Tengo dos arrays, devueltos de dos consultas a la base de datos.

Consultas:

$  result = mysqli_query($  link, "select email from sec_users where control = 0 and active = 'Y'"); $  compVacaciones = mysqli_query($  link, "select email from solicitud as s inner join sec_users as u on u.login = s.fk_empleado where ("2019-06-12" between date(s.fecha_inicio) and date(s.fecha_fin)) and fk_estado_sup = 1 group by s.fk_empleado");  $  control = mysqli_fetch_array($  result); $  vacaciones = mysqli_fetch_array($  compVacaciones); 

Lo que intento es comparar los dos arrays y que si en el array $ control encuentra algún resultado del array $ vacaciones pues que desaparezcan del array $ control. He intentado hacer una prueba con array_intersect() y que me devuelva en un print_r() lo que deseo eliminar del array $ control, pero no me ha funcionado.

$  resultado = array_intersect($  control, $  vacaciones); print_r($  resultado); 

¿Alguna ayuda con lo que deseo hacer?

Como transformar um array em um objeto com “n” arrays de acordo com a propriedade a que ele corresponde de outro array? [pendente]

Boa tarde,

Tenho dois arrays. Um que possui todos os valores, e outro que possui identificadores que desejo filtar o primeiro array, e separar os valores em um objeto.

Exemplo:

ARRAY COM TODOS OS VALORES

const ArrayTodosOsValores =[   {     "ric": "B3SA3.SA",     "category": 3,     "categoryString": "Equity",     "arcCode": "",     "description": "B3 BRASIL BOLSA BALCAO ORD",     "ticker": "B3SA3",     "isin": "BRB3SAACNOR6",     "cusip": "",     "exchange": "BOV",     "country": "BR",     "instrType": 12,     "ricRoot": "0#.BVSP",     "hasChain": true,     "useChain": false,     "identifierTypeFound": "Ric",     "historyMonths": 3   },   {     "ric": "BBAS3.SA",     "category": 3,     "categoryString": "Equity",     "arcCode": "",     "description": "BANCO DO BRASIL ORD",     "ticker": "BBAS3",     "isin": "BRBBASACNOR3",     "cusip": "",     "exchange": "BOV",     "country": "BR",     "instrType": 12,     "ricRoot": "0#.BVSP",     "hasChain": true,     "useChain": false,     "identifierTypeFound": "Ric",     "historyMonths": 3   },   {     "ric": "1ZEG1",     "category": 1,     "categoryString": "Derivatives",     "arcCode": "",     "description": "ETHANOL FEB1",     "ticker": "EH",     "isin": "",     "cusip": "",     "exchange": "CBT",     "country": "US",     "instrType": 9,     "ricRoot": "0#1ZE:",     "hasChain": true,     "useChain": false,     "identifierTypeFound": "Ric",     "historyMonths": 3   },   {     "ric": "1ZEG9",     "category": 1,     "categoryString": "Derivatives",     "arcCode": "",     "description": "ETHANOL FEB9",     "ticker": "EH",     "isin": "",     "cusip": "",     "exchange": "CBT",     "country": "US",     "instrType": 9,     "ricRoot": "0#1ZE:",     "hasChain": true,     "useChain": false,     "identifierTypeFound": "Ric",     "historyMonths": 3   }, ] 

ARRAY DE IDENTIFICADORES

 const arrayIdentificadores = ["0#.BVSP", "0#1ZE:"]  

Quero que o ArrayTodosOsValores seja filtrado atráves da propriedade ricRoot, com os valores do arrayIdentificadores, resultando no seguinte objeto:

const resultado = {   0#.BVSP: [   {     "ric": "B3SA3.SA",     "category": 3,     "categoryString": "Equity",     "arcCode": "",     "description": "B3 BRASIL BOLSA BALCAO ORD",     "ticker": "B3SA3",     "isin": "BRB3SAACNOR6",     "cusip": "",     "exchange": "BOV",     "country": "BR",     "instrType": 12,     "ricRoot": "0#.BVSP",     "hasChain": true,     "useChain": false,     "identifierTypeFound": "Ric",     "historyMonths": 3   },   {     "ric": "BBAS3.SA",     "category": 3,     "categoryString": "Equity",     "arcCode": "",     "description": "BANCO DO BRASIL ORD",     "ticker": "BBAS3",     "isin": "BRBBASACNOR3",     "cusip": "",     "exchange": "BOV",     "country": "BR",     "instrType": 12,     "ricRoot": "0#.BVSP",     "hasChain": true,     "useChain": false,     "identifierTypeFound": "Ric",     "historyMonths": 3   }],   0#1ZE:[   {     "ric": "1ZEG1",     "category": 1,     "categoryString": "Derivatives",     "arcCode": "",     "description": "ETHANOL FEB1",     "ticker": "EH",     "isin": "",     "cusip": "",     "exchange": "CBT",     "country": "US",     "instrType": 9,     "ricRoot": "0#1ZE:",     "hasChain": true,     "useChain": false,     "identifierTypeFound": "Ric",     "historyMonths": 3   },   {     "ric": "1ZEG9",     "category": 1,     "categoryString": "Derivatives",     "arcCode": "",     "description": "ETHANOL FEB9",     "ticker": "EH",     "isin": "",     "cusip": "",     "exchange": "CBT",     "country": "US",     "instrType": 9,     "ricRoot": "0#1ZE:",     "hasChain": true,     "useChain": false,     "identifierTypeFound": "Ric",     "historyMonths": 3   },  ] }  

Como posso fazer isso? Muito obrigada.

Version 2 – print new even-length arrays from two arrays

This is an update of the code for my previous post for the GeeksForGeeks task.

Task outline

Given two arrays, print all new arrays of even length where each subsequent element in the new array comes alternately from A then B and each element is larger than the previous element

Example:

  • Array 1 = [1, 2, 3]
  • Array 2 = [2, 4, 6]

Possible new array lengths = [2, 4, 6]

The output for arrays of length 2 is: [1,2], [1,4], [1,6], [2,4], [2,6], [3,4] [3,6]

The full solution for the above includes the following two additional arrays: [1 2 3 4], [1 2 3 6]

This solution uses the itertools library

import itertools A=[10, 20, 30,40] B=[11,21,31,41] list_solutions = []   for x in range (1,min(len(A),len(B))+1):     newA = list(itertools.combinations(A,x))     newB = list(itertools.combinations(B,x))     for itemA in newA:         for itemB in newB:             to_print = True              for index in range (min(len(itemA),len(itemB))):                 if itemA[index] >= itemB[index]:                      to_print = False                      break              if to_print == True:                  list_solutions.append([itemA, itemB])  #Print only valid solutions: for item in list_solutions:     print_valid = True      for index in range (len(item[0])):         if item[0][index] >= item[1][index]:             print_valid = False              break          if index >= 1:             if item[0][index] <= item[1][index-1]:                 print_valid = False                 break      if print_valid == True:         for index in range (len(item[0])):             print (item[0][index], item[1][index], sep = " ", end = " ")         print ("")     if print_valid == False:         continue   

Sorted sub-arrays from 2 arrays

Problem

For two lists, A and B (e.g:

A = [1,3,5]  B = [2,4,6]  

Find all new sequences of length % 2= 0 where each subsequent element i the new sequence is alternately taken from list A or list B and ends with an element from list B. Each new element in the sequence must be larger than the previous largest element.

For example: strings of length 2 include

  • 1,2
  • 1,4
  • 1,6
  • 3,4
  • 3,6
  • 5,6

New sequences can be of lengths 2, 4 and 6

I am aware this code is exceptionally inefficient and has a time complexity close to O(n^4) as it has 4 nested loops of sorts, but I couldn’t work out a better method

It is however much faster than the method on GeeksForGeeks

A = [1,3,5]  B = [2,4,6]  stored = []  #Work out the maximum  length of a valid subsequence max_length = len(B) + len(A) - (max(len(A), len(B)) - min(len(A), len(B)))  for x in range (2, max_length + 1, 2): #Incremenet in steps of 2      for item in A: #Take each element in A         for start_B in range(len(B) + 1): #Gets an index so a copy of B can be made             new_A = A[:]             new_B = B[start_B:] #Uses index to create copy of B starting from start_B             output_array = []             index = 0              turnA = True              while new_A or new_B:                     if output_array == []:                      output_array.append(item)                     new_A.remove(item)                     turnA = False                  if turnA and new_A:                     if new_A[0] > output_array[-1]:                          output_array.append(new_A[0])                         turnA = False                      new_A.pop(0)                 elif turnA == False and new_B:                     if new_B[0] > output_array[-1]:                          output_array.append(new_B[0])                         turnA = True                     new_B.pop(0)                 else:                     break                  if len(output_array) == x:                     if output_array not in stored:                         print(output_array)                         stored.append(output_array[:])                     output_array.pop()                     if turnA == False:                         turnA == True                     else:                         turnA = False