Pregunta sobre ejercicio de Arrays en JavaScript

tengo una duda sobre javascript, que cuando hago una prueba me devuelve undefined deepEquap “oro” por ejemplo, si hago medallaSegunPuesto(1), no entiendo que es este error asi que si me pueden explicar que es y que esta mal se lo agradecería. Básicamente tengo que pasar por parámetro un puesto y la función tiene que devolverme la medalla que corresponda

   function medallaSegunPuesto(puesto){         var puestos = ["oro", "plata", "bronce", "nada", "nada"];         var posicion = puestos.indexOf(puestos[puesto]);         if((posicion + 1) == puesto){                console.log(puestos[puesto]);        }        } 

recorrer 2 arrays en javascript (ajax)

tengo una peticion ajax en mi sistema, en el cual estoy devolviendo 2 arreglos, uno llamdo $ data y otro llamado $ data1.

lo que quiero hacer es poder recorrer el valor que tiene cada array.

el retrun lo estoy haciendo de la siguiente manera return response()->json([$ data,$ data1]); En laravel.

a la vista legan los 2 arreglos pero no se como recorrer ambos

Generate all combinations of values that are less than array’s elements and have a sum = target

I want to find a way to generate sets that contain elements that sum to a certain target. Initially, I have an array that contains elements representing the maximum value that can be stored in that index.

For example, the input is [8,6,1] and the target is 10. The algorithm should produce all sets that have elements [ (<=8), (<=6), (<=1) ] such that their sum is equal to 10. Examples include: [8,1,1], [8,2,0], [7,3,0], …

A major consideration for this algorithm is that it should work on any input length (the above example has a length of 3).

I think the solution is close to the subset sum problem, but I wasn’t able to figure it out. Any help is appreciated.

Side note: python code is preferred, but Pseudo-code should be fine.

Thanks

Counting common values in two arrays


given two arrays of integers A and B of size m, with values in the range [-n,n]. I want an algorithm to count how many common values are in A and B , if a value is repeated we only count it once , for example : $ A=\{2,2,14,3\}$ and $ B=\{1,2,14,14,5\}$ the algorithm should return 2 . Problem is I need to do this in $ O(m)$ time.

My attempt was to create an array $ C$ , of size $ 2n$ . and increment all the values of $ A$ and $ B$ by $ n$ , and count the values of $ A$ like: $ C[A[i]] = 1$ that would take me $ O(m)$ time , and $ O(1)$ time to create the array. then going over $ B$ and counting how many $ 1’s$ I encounter in $ C$ .

So far it sounds good, however I have no idea what’s in $ C$ in the first place and it could be that there’s a $ 1$ in there already and that would increment the counter falsely , and initializing $ C$ would take $ O(n)$ time.

Any ideas? Thanks ahead.

arrays indexados que no pueden ser ordenados

Array ( [searchResult] => Array     (         [search] => Array             (                 [results] => Array                     (                         [nombre] => Array                             (                                 [0] => victor                                 [1] => ivan                             )                         [cargo] => Array                             (                                 [0] => programador                                 [1] => programador                             )                         [sueldo] => Array                             (                                 [0] => 1                                 [1] => 2                             )                     )             )     ) ) 

tengo un problema al momento de poder ordenar este array, ya que no consigo poder hacer que los index vayan juntos, es decir:

  • [0] victor
  • [0] programador
  • [0] 1

  • [1] ivan

  • [1] programador
  • [1] 2

sin embargo la respuesta que obtengo al recorrer los arrays es la siguiente:

  • [0] victor
  • [0] ivan

  • [1] programador

  • [1] programador

  • [2] 1

  • [2] 2

Espero alguien pueda ayudarme con este problema, adjunto el código que estoy usando. De antemano gracias!!

foreach($  food as $  resultado => $  nivel1) { echo "<b> $  resultado </b>"; echo "<hr>"; foreach($  nivel1 as $  indice => $  indice1) {     //echo "<p> $  indice </p>";     foreach($  indice1 as $  indice2 => $  indice3) {         //echo "<p> $  indice2 </p>";         foreach($  indice3 as $  indice4 => $  indice5) {             echo "<b><p> $  indice4 </p></b>";             echo "<br>";             foreach($  indice5 as $  indice6 => $  valor) {                 echo $  indice6. " ". "$  indice4 " . "" . $  valor;                 echo "<br>";             }         }     } } 

}

concatenate string arrays – algorithm flowchart interpretation

I would like help interpreting this flowchart. I don’t know what k means even though they say what it represents in the question.

I can quickly see that since dimension m corresponds to variable X that the first loop has to be iterating on X. Therefore A has to be X(k) → Z(k).

Since I know the first loop is on X, obviously the second loop is on Y. Therefore B is Y(k) → Z(?+k).

Where I get stuck is choosing (m+k) or (n+k). What exactly does k represent?
The question says that variable k varies from 1 to m by 1.

m is the number of elements in the array (the dimension).
k is the iterator?
variable k varies from 1 to m by 1means that k varies from 1 element to m elements right?
I know the answer is (m+k) but why isn’t it (n+k)?

If possible could you please explain it in both C & Java using the same variable names? Thank you.

enter image description here

Time complexity of quicksort for arrays in increasing or descreasing order

Two $ n$ -size arays are given: $ n_1$ is in decreasing order and $ n_2$ is in increasing order.

Let $ c_1$ be the time complexity for $ n_1$ using quicksort, and $ c_2$ the time complexity for $ n_2$ using quicksort.

I think $ c_1 = c_2$ and $ c_1=O(n^2)$ ? Is this correct ?

I am using the last element as a pivot for each partition.

Map vs. Table for index-specific operations on 2D arrays

Many experienced users on this site tend to use Map (and its variants, MapAt, MapIndexed, etc.) rather than Table. When applying the same operation to every element of an array, Map does seem more semantically direct. For instance:

test2D = {{a1, a2, a3}, {b1, b2}, {c1, c2, c3, c4}}; Table[g[test2D[[row, col]]] + 1, {row, 1, Length@test2D}, {col, 1, Length@test2D[[row]]}]; MatrixForm[%, TableAlignments -> Left] Map[g[#] + 1 &, test2D, {2}]; MatrixForm[%, TableAlignments -> Left] 

But when I need to carry out index-specific (i.e., position-specific) operations on higher-dimensional(>=2D) arrays, I find Map and its variants more challenging than Table.

For instance, suppose I want to raise each element in a 1D array to a power equal to its position. That I can do with either Table or MapIndexed:

test1D = {a1, a2, a3}; Table[test1D[[col]]^col, {col, 1, Length@test1D}] Flatten[MapIndexed[#1^#2 &, test1D], 1] 

But suppose I want to raise each element in a 2D array to a power equal to its row no. x column no. With Table that’s conceptually straightforward:

Table[test2D[[row, col]]^(row*col), {row, 1, Length@test}, {col, 1, Length@test2D[[row]]}] 

But how would one do that with MapIndexed? It would be nice if it were just something like:

MapIndexed[#1^(#2*#3) &, test2D] 

where #2 were the column index and #3 were the row index, but it doesn’t work like that.

Finally, suppose you have more detailed index-specific operations in a 2D array. That seems to be where Table really shines, but I’d be interested to hear of alternatives. E.g., suppose that, from each successive 4-element block of data in a row, you need to extract the 2nd and 4th elements, but only when all four elements are present. Thus, in a row of {a1, a2, a3, a4, a5, a6, a7, a8, a9, a10}, you need {{a2, a4}, {a6, a8}}. And you need to do this for each successive row. Further, the rows have variable lengths. With Table, this does the job:

test2Dx = {{a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13,  a14, a15, a16, a17, a18, a19, a20}, {b1, b2, b3, b4, b5, b6, b7,  b8, b9, b10, b11}, {c1, c2, c3, c4, c5, c6, c7}, {d1, d2, d3, d4,  d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17}};  Table[{test2Dx[[row, 2 + col*4]], test2Dx[[row, 4 + col*4]]}, {row, 1, Length@test2Dx}, {col, 0, (Floor[N[Length[test2Dx[[row]]]/4]]) - 1}];  MatrixForm[%, TableAlignments -> Left] 

Is there a semantically straightforward way to do this using other functions (e.g., Map or its variants and a pure function)—or is this a use case for which Table makes more sense?

Does the order of multidimensional array’s length affect the time complexity of accessing elements?

I was using a 3d array in java of lengths 3001,3001,4 in a dp problem but I couldn’t get my submission accepted as i kept on exceeding the time limit(1 second), i checked the code of a friend and found out that the only difference was that the order of the lengths of the memo was 4,3001,3001 as soon as i changed my memo order to the previous order my code ran in 400ms so i would like to know what is the difference between both cases

Leetcode 4: Median of Two Sorted Arrays


Task

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

You may assume nums1 and nums2 cannot be both empty.

nums1 = [1, 2] nums2 = [3, 4]  The median is (2 + 3)/2 = 2.5 

Solution

class Solution:     def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:         total_len = len(nums1) + len(nums2)         multiple = total_len % 2 == 0                            # Is the median made up of two numbers?         median_index = (total_len // 2) - (1 if multiple else 0) # The first median number           i1 = 0         i2 = 0          len1 = len(nums1)         len2 = len(nums2)          median_sum = 0          for i in range(total_len):             if i1 >= len1:                 cur = nums2[i2]                 i2 += 1             elif i2 >= len2:                 cur = nums1[i1]                 i1 += 1             else:                 n1 = nums1[i1]                 n2 = nums2[i2]                  if n1 <= n2:                     cur = nums1[i1]                     i1 += 1                 elif n2 < n1:                     cur = nums2[i2]                     i2 += 1              if i == median_index:                 if multiple:                     median_sum += cur                 else:                     return float(cur)             if i == median_index + 1:                 return (median_sum + cur) / 2 

The code runs as expected, but can I improve its performance or make it more readable?