algorithms – sort array using oracle computes number of elements in one partition that are smaller than given element in O(1)

excuse me for the long title. My goal is to find an algorithm to sort an array of n elements, with an oracle, which must be used O(logn) times.
Given a partition of our array (resulting in two subsets, A and B), this oracle can tell us how many elements in B are smaller than a given element in A in O(1).
A naive approach would be partitioning the array to an element and a subarray of n-1 elements, and using the oracle to determine the position of our single element. Doing this n times would sort the array in O(n).
However I cannot think of any algorithm that would perform better than O(n), and I am beginning to question whether or not this is possible?
thanks in advance!

c# – How do you find the maximum number in a set of integers within an array?

My professor wants us to use this format to create an array with these numbers. He also wants us to find the maximum number without using library methods (eg: array.Max()), but with loops and Int.minValue. However, I cannot seem to properly print out “9,” which is the obvious answer. It keeps printing random numbers as the maximum value. Here is the code I tried below VVV

            Console.Write("The stored values aren");

            int() nums = new int() { 5, 8, 9, 4, 2 };
            int i = 0;

            while (i < 5)
            {
                Console.Write(nums(i) + " ");
                ++i;
            }

            int highestFound = int.MinValue;

            if (highestFound < i )
            {
                Console.Write("nThe maximum value is " + highestFound + ".");
            }

            Console.ReadKey();

c++ – Implementing Floyd’s APSP Algorithm with a 3-dimensional array

I am having trouble implementing this algorithm in the way that my instructor wants it. I understand the basic algorithm with a 2D array passed to the function, but this requires a 3D array as a parameter and I’m not sure how to work around it. Any insight would be greatly appreciated! I have attached an image of the question at hand. It states to write the solution in Cilk but I am first trying to implement it in C++. Image of the problem

array – Concatena las cadenas en C

¿Cómo puedo concatenar dos cadenas dejando un espacio en blanco entre medias?

Ejemplo:

Cadena1

Hola

Cadena2

Mundo

Salida deseada

Hola Mundo

He estado usando strcat (cadena1, cadena2) pero esto me saca

HolaMundo

Conocéis alguna forma para solucionarlo.

PD: Tanto cadena1 como cadena2 están definidas como char cadenaX(250), donde X es el número de la cadena.

Muchas gracias de antemano

plotting – How to reverse the order in which ListPlot plots multiple array of numbers?

list = {{1, 2}, {1, 2, 3}, {1, 2, 3, 4}};

Add x-coordinates to each data point using MapIndexed + Thread:

list2 = MapIndexed[Thread[{#2[[1]], #}] &, list]
{{{1, 1}, {1, 2}}, 
 {{2, 1}, {2, 2}, {2, 3}},
 {{3, 1}, {3, 2}, {3, 3}, {3, 4}}}
ListPlot[list2, PlotStyle -> PointSize[Large], PlotLegends -> InputForm /@ list]

enter image description here

You can also use MapThread + Thread to construct list2:

list2 = MapThread[Thread[{##}] &, {Range@Length@list, list}]
{{{1, 1}, {1, 2}}, 
 {{2, 1}, {2, 2}, {2, 3}},
 {{3, 1}, {3, 2}, {3, 3}, {3, 4}}}

php – No puedo mostrar todos los elementos de un array, solo veo el ultimo la cantidad de veces que hay de elementos en el array

Cordial saludo para todos, me encuentro tratando de solucionar un problema, al momento de mostrar en pantalla todos los elementos de un arreglo solo me muestra el ultimo y se repite la cantidad de veces que hay de elementos en el arreglo.

Con esto obtengo el arreglo

$column_izquiera = explode(',', $opigno_activity->get('field_palabras_izquierda')->getString());

El cual se ve así:

Array
(
    (0) => puya
    (1) =>  pelo
    (2) =>  pino
    (3) =>  pila
    (4) =>  peca
    (5) =>  loca
)

Y esta es la forma en la cual estoy recorriendo el arreglo para mostrar todos los elementos:

foreach ($column_izquiera as $words) {
      $variables('column_left') = $words;
    }

Y esto es lo que obtengo:

loca
loca
loca
loca
loca
loca

Y pues sabrán que lo que necesito es obtener algo así:

puya
pelo
pino
pila
peca
loca

Por favor necesito de su ayuda muchas gracias, para mostrarlo se utiliza twig de esta manera

<div class="content">{{ column_left }}</div>

matlab – Ejecutando DLL con array como input desde VBA: error 91Variable de objeto o bloque with no establecido

He escrito un código en VBA para que ejecute una DLL creada mediante Matlab. La función de Matlab convertida en DLL tiene como input un structure array de varios tipos de datos (números, texto, ruta). He referenciado bien la librería DLL en VBA y mi intención con este código es lanzar la DLL al pulsar un botón leyendo los datos desde una hoja Excel y metiéndolos en un array para usarlo como parámetro de entrada al llamar a la DLL. El código que se ejecuta al pulsar el botón se encuentra en “Sub Boton_Lanzar_Calculo()”

Este es el código:

Dim MCLUtil As Object
Dim bModuleInitialized As Boolean
Dim aClass As VictorCalc_main.Class1


''' Include a call to InitModule at the beginning to ensure that the initialization alwais gets performed as needed
Private Sub InitModule()
   If Not bModuleInitialized Then
      On Error GoTo Handle_Error
      If MCLUtil Is Nothing Then
         Set MCLUtil = CreateObject("MWComUtil.MWUtil")
      End If
      Call MCLUtil.MWInitApplication(Application)
      bModuleInitialized = True
      Exit Sub
Handle_Error:
      bModuleInitialized = False
   End If
End Sub

'New operator:
Function recorrido(ByVal inputscript As Variant) As Variant
       
       On Error GoTo Handle_Error
       Set aClass = New VictorCalc_main.Class1
       aClass = CreateObject("VictorCalc_main.Class1.1_0")
       Call aClass.recorrido(inputscript)
       Exit Function
Handle_Error:
   recorrido = Err.Description
End Function
 
 Sub Boton_Lanzar_Calculo()
 
   Dim inputscript() As Variant

   ReDim inputscript(11)

   inputscript(0) = Range("Sentido")
   inputscript(1) = Range("Paso_tiempo")
   inputscript(2) = Range("Paso_posición")
   inputscript(3) = Range("Ruta_Archivo_Input")
   inputscript(4) = Range("Nombre_archivo_output")
   inputscript(5) = Range("Flag_tabla_límite_aceleración")
   inputscript(6) = Range("Flag_tabla_rendimiento_motor")
   inputscript(7) = Range("Flag_guardar_Excel")
   inputscript(8) = Range("Tipo_resistencia_rodante")
   inputscript(9) = Range("Tipo_resistencia_por_pendiente")
   inputscript(10) = Range("Tipo_resistencia_por_curva")
  
  Call aClass.recorrido(inputscript)
   
 End Sub

El error lo da al hacer el call a la función recorrido con el array inputscript. ¿Puede ser que no acepte los datos que quiero pasar a la DLL?

javascript – ¿Cómo identificar la posición de un valor en un array sin necesidad de recorrer todos los elementos?

pues tal y como pone en el titulo no se como hacer para que marque la posición del un valor del array sin recorrer todos los elementos en este caso quiero sacar el valor 5, aquí mi código que llevo hasta ahora:

function numeros(){
var numeros1 = (4,0,3,4,8,5,3,1,4,8,4,3,2,6,1,8,9,7,8,5,0,1,5);
let greaterTen2 = numeros1.filter(number => number = 5 );

alert(greaterTen2)
}

algorithm – Given a 2D array, how do I generate a random path of fixed length from a random point at length 0 to a random point at max length?

I’m trying to generate a random path on a 2D grid given that:

  • The width and height of the grid are given
  • The length of the path to generate is given
  • The path can’t move “back”
  • The path starts from a random point at height 0 and ends at a random point at max height
  • A path segment cannot “touch” with a path segment that is at its height – 1 that is not the latest generated segment of the previous height

This is what two paths generated from the parameters {Width:11, Length:17, PathLength:30} would look like:

generated path example 1
generated path example 2

and this is an example of a path that should not be generated:

Bad example

The result of the algorithm should be a list of value pairs such as this: (8,6) in any order, which indicates the segments of the path.
I’ve been trying to solve this problem for a while, but I have problems understanding how to make this have a given length. If the given length was not a requirement I could just generate it with a nested for cycle and some rules. Please help!

plugin development – Callback is not called in add_settings_field() when passed as part of an array, but recognises that it’s there. It’s passed Class to Class using OOP

I am building a plugin, I created a new admin page and subpage, and inside that subpage, I want to add some Settings. That’s why I’m building them using the Settings API.
I am using Composer and Object-Oriented Programming. I have a folder called SettingsAPI, with the following namespace namespace BlocksPagesSettingsAPI;
Inside that folder, I have three files: AddSettings.php, Settings.php and SettingsLayout.php. All three of them are correctly connected. The files have the case sensitive names of the Classes. Settings.php has a Class named Settings, and so on.

SettingsAPI Folder Structure

Content

  • Some Context to my Structure
  • What I have already tried
  • What to do?

Inside Settings.php I have a function that holds a variety of arrays, inside of those arrays are the values I want to use for the Settings API. This means I have arrays that are used for register_setting(), add_settings_section() and add_settings_field().
Inside AddSettings.php I have the three functions just mentioned. Both register_settings() and add_settings_field() work great. I have problems with add_settings_field().
Inside SettingsLayout.php I have a very simple layout for where the form should be printed, which is also shown on the Subpage. Just the inputs are missing.

Inside AddSettings.php I used a foreach() to loop over the array, if I need to. Which is used for both register_setting() and add_settings_field(), that’s because both of those arrays have arrays inside of them. I’ll show some code used for register_setting() and the foreach().

Settings.php

$configs = (
      ( // Icon
        "option_group"    =>    "iw_" . $n,
        "option_name"     =>    "iw_icon_" . $n,
        "args"            =>    $iconConfigs
      ),
      ( // Titel
        "option_group"    =>    "iw_" . $n,
        "option_name"     =>    "iw_title_" . $n,
        "args"            =>    $titleConfigs
      ),
      ( // Beschreibung
        "option_group"    =>    "iw_" . $n,
        "option_name"     =>    "iw_description_" . $n,
        "args"            =>    $descriptionConfigs
      ),
      ( // Farbauswahl
        "option_group"    =>    "iw_" . $n,
        "option_name"     =>    "iw_colour_" . $n,
        "args"            =>    $colourConfigs
      )
    );

The array above is being passed, alongside the other arrays, to the AddSettings Class and the next function that will process them.

$this->add_settings->setForm( $configs, $segments, $inputs )->register();

setForm() does the following with the arguments.

AddSettings.php

public  function  setForm(  array  $configs,  array  $segments,  array  $inputs )  {
    $this->settings =  $configs;
    $this->sections =  $segments;
    $this->fields =  $inputs;
    return  $this;
}

The variables $settings, $sections and $fields have been created at the beginning of the class as public and empty arrays.

public $settings = array();
public $sections = array();
public $fields = array();

Which then gets registered with the following function:

public  function  functionToAdd()  {
return  $this->registerForm(  $this->settings,  $this->sections,  $this->fields );
}

registerForm() hold all the Settings API functions from WP, here is register_setting().

foreach( $this->settings as $setting ) {
      register_setting( $setting("option_group"), $setting("option_name"), isset( $setting("args") ) ? $setting("args") : "" );
    }

This part works great. It also works with add_settings_section(). What doesn’t work, are the inputs. Which I will present now as well:

Settings.php

Inside this Class is the function/method setForm( $n = NULL ), that’s where all the arrays are, like the one I showed above. Right now $n has no meaning, but it’s going to be a number, so I can loop all over those arrays and settings to create more forms. Whether I keep it at NULL or I change it to 1, has no effect on the endresult, same thing.
Here is the array for the fields.

$inputs =  (
    (
        "id"  =>  "iw_icon_"  .  $n,
        "title"  =>  "Icon Auswahl",
        "callback"  =>  function()  use($n)  {  return  $this->iconInput(  $n );  },
        "page"  =>  "info_kreis_bearbeiten",
        "section"  =>  "iw_item_"  .  $n,
        "args"  =>  (  "label_for"  =>  "iw_icon_"  .  $n )
    ),
    (
        "id"  =>  "iw_title_"  .  $n,
        "title"  =>  "Titel",
        "callback"  =>  function()  use($n)  {  return  $this->titleInput(  $n );  },
        "page"  =>  "info_kreis_bearbeiten",
        "section"  =>  "iw_item_"  .  $n,
        "args"  =>  (  "label_for"  =>  "iw_title_"  .  $n )
    ),
    (
        "id"  =>  "iw_description_"  .  $n,
        "title"  =>  "Kurz Beschreibung",
        "callback"  =>  function()  use($n)  {  return  $this->descriptionInput(  $n );  },
        "page"  =>  "info_kreis_bearbeiten",
        "section"  =>  "iw_item_"  .  $n,
        "args"  =>  (  "label_for"  =>  "iw_description_"  .  $n
    ),
    (
        "id"  =>  "iw_colour_"  .  $n,
        "title"  =>  "Farbe auswählen",
        "callback"  =>  function()  use($n)  {  return  $this->colourInput(  $n );  },
        "page"  =>  "info_kreis_bearbeiten",
        "section"  =>  "iw_item_"  .  $n,
        "args"  =>  ( "label_for"  =>  "iw_colour_"  .  $n )
    )
);

So this is an array with three arrays inside of it. This array has callbacks, and it’s the callbacks that do not work at all. No matter where I put them or how I write them, they are not being echo’d. At the bottom I will list all of the things I have tried.
Like with the settings arrays, they are allso processed like this:

$this->add_settings->setForm( $configs, $segments, $inputs )->register();

AddSettings.php

And then

public  function  setForm(  array  $configs,  array  $segments,  array  $inputs )  {
    $this->settings =  $configs;
    $this->sections =  $segments;
    $this->fields =  $inputs;
    return  $this;
}

and

public  function  functionToAdd()  {
return  $this->registerForm(  $this->settings,  $this->sections,  $this->fields );
}

Which then gets passed to registerForm() with the following function:

foreach(  $this->fields as  $field)  {
    add_settings_field( $field("id"), $field("title"), isset( $field("callback") ) ? $field("callback") : "", $field("page"), $field("section") = 'default', $field("args") = array() );
}

And then nothing. No inputs on my Subpage. Everything but the fields are being echo’d.
Form on Subpage
As you can see, the callback used by the section works and shows me the title and description. But the inputs are missing. To show some context on how I called the callback for the sections, here is the one line with the callback from the section array, inside Settings.php:

"callback"  =>  function()  use($n)  {  echo  "<p>Bearbeite hier die Info Nummer "  .  $n .  "</p>";  }

And the function add_settings_section() inside AddSettings.php, no foreach() was used for this one:

add_settings_section(  $sections("id"),  $sections("title"), isset(  $sections("callback")  )  ?  $sections("callback")  :  "",  $sections("page")  );

It’s being called the same way like the fields. But the fields still do not echo anything. Any before anyone says I am echoing inside the anonymous callback function instead of returning another function:

I have tried a few things. One of the first things I tried was to edit the way the callback is written. So instead of a function that returns another function I wrote something simple.

"callback"  =>  function()  {  echo "Echo this please."; },

Didn’t work.

"callback"  =>  array( $this, "iconInput" ),

Also not working
I also tried

"callback"  =>  $this->iconInput( $n ),

Which then called the function and echo’d the inputs, but not in the right position. They were at the very top of the page. And if I loop everything, all inputs will be at the top, with the sections below in the right print order. So that’s not the solution either.
What I also tried was to move the callback to AddSettings.php and call it like that.

add_settings_field(  $field("id"),  $field("title"),  function()  { return $this->iconInput();  },  $field("page"),  $field("section")  =  'default',  $field("args")  = array()  );

Didn’t work either.
When I tried to just directly write the function in there, like so

add_settings_field(  $field("id"),  $field("title"),  function()  { echo "Please echo this";  },  $field("page"),  $field("section")  =  'default',  $field("args")  = array()  );

Didn’t work either. I also always put die; at the end, just to see if it’s being called at all, and it has not been. It’s like the function doesn’t exist.
I have also tried to immediately run the function by adding () to it:

add_settings_field( $field("id"), $field("title"), isset( $field("callback") ) ? $field("callback")() : "", $field("page"), $field("section") = 'default', $field("args") = array() );

Same result like earlier. It echo’d the inputs, but not in the right position.

I tried looking for an answer, but couldn’t really find one that was similar to mine. I found these questions and solution, tried them, and that also didn’t work:
How to pass arguments from add_settings_field() to the callback function?
and
Add_settings_field() parameterizing callback?

And for clarification, my SettingsLayout.php is build like this:

<form  method="post"  action="options.php"  id="iw_form_<?php  echo  $i?>">
    <?php
        settings_fields(  "iw_"  .  $i  );
        do_settings_sections(  "info_kreis_bearbeiten"  );
        submit_button(  $text  =  NULL,  $type  =  "primary",  $name  =  "submit_"  .  $i  );
    ?>
</form>

$i is the same as $n.

I have run out of options to try. At least of options I know of. If anyone has any kind of solution, I would be HAPPY to hear them. I also explained myself as best as I could.

And because that’s a lot of code, pasted the relevant code into the online editor for you to look at even better: https://repl.it/@Braweria/Callback-Problems

Edit

Which I forgot to mention, inside my foreach() I also echoed field("id") to see if that works, and it does echo the right ID.