Given an array of size n, create a sub array with given cinditions using dynamic programming

We are given an array of integers of size n, which is not necessarily sorted, and we want to create a sub array. We are allowed to do one of 3 tasks below in each level: 1. skip the number in original array and go to the next 2. insert the number in the start of the sub array 3. insert the number in the end of the sub array.
And at last we want the sub array to be the longest one that can be created with the conditions above and sorted. For example we have A={10,3,13} now we can insert 10 in the beginning, skip 3 and insert 13 in the end. so the size of sub array is 2.

I know that I must solve this using dynamic programming but I do not know how to do it exactly.

Accessing/Adding to a 2D C++ array using inline assembly

I’m trying to create an encryption/decryption program using c++ and assembly. I was originally using 3 different arrays, the original string, the encrypted string, and the decrypted string. I’m now trying to convert this to a 2D array and I’m having trouble adding an encrypted character to the second line of the array.

  __asm   {             push    eax                                  push    ebx                                  push    ecx                                  push    edx                                   xor     ebx, ebx                             jmp     checkend                     forloop1: add ebx, 1                           checkend: cmp ebx, aLength                             jge endfor1                                   movzx   ecx, byte ptr[Chars + ebx]           lea     eax, EKey                            push    ecx                                  mov     edi, eax                             movzx   eax, byte ptr[eax]                   and     eax, 0x3f                            rol     al, 1                                mov     byte ptr[edi], al                    cmp     eax, 0x00                            jnz     zerocheck                            mov     eax, 0x09                   zerocheck:mov     edx, eax                             pop     eax                                  sub     eax, edx                             rol     al, 1                                not     al                                   mov     byte ptr [Chars + ebx * 2], al       // this line here          jmp     forloop1                     endfor1:                                                pop     edx                                  pop     ecx                                  pop     ebx                                  pop     eax                           } return; 

I can read in the first row fine, which is where the string entered is stored. I’ve marked the line where I’m trying to get the encrypted character to be stored in the second line the array but everything I’ve tried doesn’t seem to work. Any help would be appreciated.

Remove and Add items from array in nested javascript object

I have the following object at React state:

groups: [     {         id: 1,         items: [             {id: 1},             {id: 2},             {id: 3}         ]     },     {         id: 3,         items: [             {id: 1},             {id: 3},             {id: 4}         ]     } ] 

I have written the following functions to add and remove items:

  removeItem(groupId, itemId) {     // make a copy     let {groups} = this.state      const gIndex= groups.findIndex(g=> g.id == groupId);     let items = groups[gIndex].items     groups[gIndex].items = items.filter((i) => i.id !== itemId)      this.setState({groups})   }    addItem(groupId, itemId) {     // make a copy     let {groups} = this.state       const gIndex = groups.findIndex(g => g.id == groupId);     let items = groups[gIndex].items     groups[gIndex].items = items.concat({id: itemId})      this.setState({groups})   } 

Is there any way to write it cleaner?

Inserir valor num array

Boas, estou a tentar inserir um valor num array que recebo de uma base de dados.

O array contem um conjunto de arrays sendo que cada array desse conjunto corresponde a uma viatura. Eu quero pegar em dois valores de cada viatura, calcular a diferença e de seguida criar um valor no array dessa viatura com a diferença calculada.

Eu estou a tentar fazer da seguinte maneira :

foreach ($  viaturas as $  key => $  viatura) {         if($  viatura['kms'] < $  viatura['inspecao1']){             $  diff = $  viatura['inspecao1'] -$  viatura['kms'];         }elseif ($  viatura['kms'] < $  viatura['inspecao2']) {             $  diff = $  viatura['inspecao2'] -$  viatura['kms'];         }elseif ($  viatura['kms'] < $  viatura['inspecao3']) {             $  diff = $  viatura['inspecao3'] -$  viatura['kms'];         }elseif ($  viatura['kms'] < $  viatura['inspecao4']) {             $  diff = $  viatura['inspecao4'] -$  viatura['kms'];         }elseif ($  viatura['kms'] < $  viatura['inspecao5']) {             $  diff = $  viatura['inspecao5'] -$  viatura['kms'];         }elseif ($  viatura['kms'] < $  viatura['inspecao6']) {             $  diff = $  viatura['inspecao6'] -$  viatura['kms'];         }elseif ($  viatura['kms'] < $  viatura['inspecao7']) {             $  diff = $  viatura['inspecao7'] -$  viatura['kms'];         }elseif ($  viatura['kms'] < $  viatura['inspecao8']) {             $  diff = $  viatura['inspecao8'] -$  viatura['kms'];         }elseif ($  viatura['kms'] < $  viatura['inspecao9']) {             $  diff = $  viatura['inspecao9'] -$  viatura['kms'];         }elseif ($  viatura['kms'] < $  viatura['inspecao10']) {             $  diff = $  viatura['inspecao10'] -$  viatura['kms'];         }         array_push($  viatura, $  diff);       } 

Mas ele não acrescenta o valor no fim de cada viatura, o que é que estou a fazer de errado?

Também já tentei usar $ viatura['diff'] = $ diff; mas não resultou

How many possible ways to go right and up in an array

Let’s say we have a 2D matrix, and we begin at (0, 0).

We must travel m steps to the right and n steps up, in any order. Each step moves the position right or up by 1.

For example if n = 5 and m = 4, the following would all be valid:

UP UP UP UP RIGHT RIGHT RIGHT RIGHT UP  RIGHT UP RIGHT UP RIGHT UP RIGHT UP RIGHT UP UP  UP UP RIGHT RIGHT UP RIGHT UP UP RIGHT 

How many possible different ways are there to travel up n times and right m times, if the ordering in which we travel right or up does not matter, as long as we start at (0, 0) and finish at (n, m)

How to efficiently get combinations of array of tuples [int, string] and compare it?

Just wondering if there is a way to run the piece of code below more efficiently. I just started to get acquainted with parallel program and think this might be an answer? But I have no idea how to do it using imap or processes…any help?

This is what the function is doing: it gets two arrays of tuples with 5 items each – hand = [H1,H2,H3,H4,H5] and board = [B1,B2,B3,B4,B5]

What I need to do is check all arrays formed by 2 items from hand and 3 items from board, like combination = [Hn,Hm,Bi,Bj,Bk] (100 combinations in total)

Then I need to compare each one of the combinations against a dictionary to get the combination rank, and then return the best array (best rank) and the rank itself:

def check_hand(hand, board, dictionary_A, dictionary_B):   best_hand = []  first_int = True   for h1 in range (0, 4):   for h2 in range (h1+1, 5):    for b1 in range (0, 3):     for b2 in range (b1+1, 4):      for b3 in range (b2+1, 5):       hand_check = []       hand_check.append(mao[m1])       hand_check.append(mao[m2])       hand_check.append(board[b1])       hand_check.append(board[b2])       hand_check.append(board[b3])       hand_check = sort(hand_check) #Custom sort for my array of objects       hand_ranks = "".join([str(hand_check[0].rank),str(hand_check[1].rank),str(hand_check[2].rank),str(hand_check[3].rank),str(hand_check[4].rank)])        if (hand_check[0].suit == hand_check[1].suit and hand_check[1].suit == hand_check[2].suit and hand_check[2].suit == hand_check[3].suit and hand_check[3].suit == hand_check[4].suit):        control = [dictionary_A[hand_ranks][0],dictionary_A[hand_ranks][1]]       else:        control = [dictionary_B[hand_ranks][0],dictionary_B[hand_ranks][1]]        if first_int:        best_hand = hand_check        rank = control        first_int = False       elif (int(control[0]) > int(rank[0])):        rank = control        best_hand = hand_check              elif (int(control[0]) == int(rank[0])):        if (int(control[1]) > int(rank[1])):                rank = control         best_hand = hand_check         return best_hand, rank[0] 

I need to run this check for 2 million different hands and interact over 1000 times for every hand (Ideally I would run it for at least 100000 times for every hand, for a more statistically accurate result). Any ideas on how to make it more efficient?

Examples:

For hand = [[‘2′,’s’],[‘5′,’h’],[‘7′,’h’],[‘8′,’c’],[‘T’,s’]] and board = [[‘3′,’s’],[‘3′,’h’],[‘9′,’s’],[‘T’,’c’],[‘6′,s’]]

It compares every combination (2s5h3s3h9s,2s5h3sTc,…., 7hTs3s9s6s,…,8cTs9sTc6s), compares to my dictionaries and returns best_hand = [[‘6′,’s’],[‘7′,’h’],[‘8′,’c’],[‘9′,’s’],[‘T’,’c’]], rank[0] = 5 (from dictionary) which is the best poker hand for this case.

For hand = [[‘8′,’s’],[‘9′,’h’],[‘9′,’c’],[‘A’,’c’],[‘A’,s’]] and board = [[‘7′,’s’],[‘6′,’h’],[‘T’,’s’],[‘T’,’c’],[‘A’,h’]] it will return best_hand = [[‘T’,’s’],[‘T’,’c’],[‘A’,’s’],[‘A’,’h’],[‘A’,’c’]], rank[0] = 7

Implement Queue using fixed size array

I came across below interview question and I am working on it:

Build a queue class with the enqueue and dequeue methods. The queue can store an UNLIMITED number of elements but you are limited to using arrays that can store up to 5 elements max.

Here is what I was able to come up with. Is this the right way to do it in the interview or is there any better way we should implement in the interview?

class Solution {     private final List<List<Integer>> array;    public Solution() {     this.array = new ArrayList<>();   }    public void enqueue(int value) {     if(array.isEmpty()) {       List<Integer> arr = new ArrayList<>();       arr.add(value);       array.add(arr);       return;     }     if(array.get(array.size() - 1).size() != 5) {       array.get(array.size() - 1).add(value);          return;     }     List<Integer> arr = new ArrayList<>();     arr.add(value);     array.add(arr);     return;   }    public int dequeue() {     if(array.isEmpty()) {       return -1;      }     for(List<Integer> l : array) {       for(int i=0; i<l.size(); i++) {         return l.remove(i);        }     }     return -1;   } } 

Как загрузить данные об изображении из numpy array чтобы выполнялась тренировка нейронной сети

У меня есть картинки иероглифов, причем каждой картинке в тренировочном сете соответствует код символа в юникод. Нужно натренировать нейронную сеть так, чтобы она классифицировала коды других иероглифов по картинкам. Тренировочный сет представлен в виде списка матриц numpy, каждая из которых описывает картинку. У меня есть процедура тренировки сети, в которую нужно загнать тренировочный набор данных. Как это сделать? Тренировочный датасет можно скачать по ссылке Как примерно выглядит датасет:

array([[array([[255, 255, 255, ..., 255, 255, 255],    [255, 255, 255, ..., 255, 255, 255],    [255, 255, 255, ..., 255, 255, 255],    ...,    [255, 255, 255, ..., 255, 255, 255],    [255, 255, 255, ..., 255, 255, 255],    [255, 255, 255, ..., 255, 255, 255]], dtype=uint8),     59076],[255, 255, 255, ..., 255, 255, 255],    [255, 255, 255, ..., 255, 255, 255],    [255, 255, 255, ..., 255, 255, 255]], dtype=uint8),     59332],...], dtype=object) 

То есть имеется набор изображений в матричном виде и код символа, соответствующий каждому изображению.

Код:

Как загружаю датасет:

import numpy as np import torch.utils.data as utils import os  os.chdir('Your directory') data = np.load('train-1.npy') 

Можно вывести на экран символы:

width, height = 8, 8 print(data[0][1]) plt.figure(figsize=(16, 20)) for n, (image, tag) in enumerate(data, 1): if n > width * height:     break plt.subplot(height, width, n) plt.title(tag)  plt.imshow(image, cmap='gray') 

Простенькая сетка (пока такая):

import torch flat_size = 71 * 71 class Net(nn.Module): def __init__(self):     super(Net, self).__init__()     self.fc = nn.Linear(flat_size, 10) def forward(self, x):     x = x.view(10, flat_size)     x = self.fc(x)     return F.softmax(x, dim=1) net = Net() 

Процедура train:

def train(model, train_loader, optimizer): model.train()  processed = 0 total = len(train_loader)  for batch_idx, (X, y) in enumerate(train_loader):     optimizer.zero_grad()   # zero the gradient buffers     probs = net(X)     loss = criterion(torch.log(probs), y)     if not batch_idx % 500:         print(f'{processed}/{total}, loss: {loss.item()}')     loss.backward()     optimizer.step()           processed += len(X)     

Код для запуска тренировки:

net = Net() optimizer = torch.optim.SGD(net.parameters(), lr=1e-3, momentum=0.9) for epoch in range(1, epoch_n+1):   print(f'Epoch {epoch}:')   train(net, data, optimizer) 

Я понимаю, что надо преобразовать в тензоры матрицы изображений и фиксировать их размер. Преобразование в тензор можно сделать прямо в цикле процедуры train:

def train(model, train_loader, optimizer): model.train()  processed = 0 total = len(train_loader)  for batch_idx, (X, y) in enumerate(train_loader):     X=torch.from_numpy(X)     optimizer.zero_grad()   # zero the gradient buffers     probs = net(X)     loss = criterion(torch.log(probs), y)     if not batch_idx % 500:         print(f'{processed}/{total}, loss: {loss.item()}')     loss.backward()     optimizer.step()           processed += len(X) 

А вот как фиксировать размер каждого изображения, пока не выяснено. В результате имеется ошибка:

RuntimeError: shape ‘[10, 5041]’ is invalid for input of size 4968

Думаю, что нужно определить единый batchsize для всех изображений..

Nome no index de um array

Preciso criar um array ou objeto, mas com nome dinâmico, tipo este do exemplo, porém o nome deve vir de uma variável:

var obj = { ‘elemento1’ : { ‘elemento1’ : ‘dado1’, ‘elemento2’ : ‘dado2’ }, ‘elemento2’ : { ‘elemento1’ : ‘dado1’, ‘elemento2’ : ‘dado2’ }, ‘elemento1’ : { ‘elemento1’ : ‘dado1’, ‘elemento2’ : ‘dado2’ }, };

Porém, quando boto o nome da variável, mesmo sem aspas, o index recebe o nome literal da variável.

É possível fazer o que estou tentando fazer?

Obs.: Desculpem se faltou alguma coisa, é a primeira vez que pergunto aqui.