instruction stringlengths 71 71.9k |
|---|
The elements in the matrix are either 'M', 'G', 'P' or '.' and the algorith must write out all possible ways of splitting the matrix so it has equal number of M, G and P on each side. It's a task we've been given to do at home. We also had to use use the matrix as a parameter in the function and use it as a pointer in ... |
The following program reads a stream and creates a two dimensional std::vector.
I'm trying to find an elegant way to handle the errors and recover from them as much as possible while still reporting the problems encountered.
It feels as though my nice clean functions are getting more and more cluttered as I add the er... |
This weekend I made an attempt at a generic repository pattern for entity framework in .NET after reading this blog post. I was wondering how it could be better. I specifically have a couple questions.
Can I be more "in line" with the typical repository pattern? I feel like I lost the typical pattern at some point and... |
This is jQuery code which works like this: depending on a user choice it changes the color and background of some elements in the DOM.
The behavior is ok, is doing exactly what I want.
And as you may see, there is some code repeated. What's the best way to keep a good performance by doing a function in order to avoid r... |
I've written a simple application that captures frames from my webcam and streams the frames via a websocket.
The stream implementation I've come up with feels weird. Networking is not my strong suit. I am wondering if the communication between the server and app can be written better.
type Stream struct {
Frame []... |
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
Explanation for using array vs ArrayList:
I could have used ArrayList and that would have been simpler while appending a 1 at the beginning b... |
For part of a project, I was given this directive:
The find command will use the directory (dirent) function calls, but
will require you to start at a directory and then determine if a file
is a directory or a file and if it is a directory you will need to
walk down that directory as well. You will need a method... |
This is improved code after I some issue in pointed by @Edward in the last question: C++ operator overloading for matrix operations
This work assignment in operator overloading .I need to use operators *, [][], =, +, -, << on objects of type matrix for example add to matrix using this code: m=m+s.
I already sent the... |
It's a few weeks old homework, and it's already graded. How can I improve my code?
Write function empty(n), which gets the board size as an argument, and returns an empty board with the given size. For instance, empty(4) must return ['', '', '', ''].
Write function isEmpty(board) returns True if the given board is emp... |
I have a need to drop quantities of elements from an iterator beyond Int.MaxValue so I wrote a helper function that does just that. However, I can't help but feel like I'm doing this the dumb way - that there's got to be some built-in language construct or at least a more elegant way of tackling the problem.
/**
* dro... |
I created a SafeQueue class, which stores pointers. It has two methods:
push: Adds a new pointer to the queue
next: If the queue is empty, returns nullptr. Otherwise it returns the front element, and pop the queue
Most of the time, I have one producer and one consumer. But there may be more.
The producer just simply ... |
At school, we have a competition where the winner is determined by the length of their unbroken sequence of expressions that evaluate to integers 0 to n.
You must use the next year's number in the correct order, every digit exactly once.
example:
0 = 2*0*17
1 = 2-01^7
2 = 2-0*17
...
The competition doesn't h... |
The system is meant to replicate the deformers and modifiers commonly used in 3D modeling programs like 3DS Max, Maya, Blender and Cinema 4D. I made a post on Reddit, explaining the features and limitations. If you (understandably) don't want to look through all the code, I'll list the important base classes.
I'm looki... |
I'm trying to learn C++ having come from a C/Assembly background. I thought one of the first tools I'd make as a project is a "directory tally" program:
It will count all the files in the current directory
If the user specifies, it will count all the folders in the current directory too
If the user specifies, it wil... |
I've been studying data structures and making implementations for different types. This is my linked list code. Please let me know if there's anything here that could be improved upon or changed for better performance. I should mention that it compiles and functions as intended.
Also, I'm not sure what I need the frien... |
I just read this post on how to avoid memory leaks with AsyncTask. The post proposed using a WeakReference and supplying a TextView as the object of the WeakReference.
In my code, I need to supply multiple parameters to the AsyncTask (not just one as shown in the post). So what I did was create an inner class with the ... |
I'm just starting out in MIPS (as is evident by the fact that I'm writing a FizzBuzz program), and my program runs fine and gives the desired output, but I feel like there is a way to do it without as many branches.
.data
fstring: .asciiz "Fizz\n"
bstring: .asciiz "Buzz\n"
hstring: .asciiz... |
Can someone please review my code? I'm saving a hotel rate to a database. I want to save the rate twice, one field will update with every new rate, and one field will contain the rate that was found for that date the first time it was captured.
The code looks very clunky and I know it can be improved.
def save_result... |
I am working on a sticky element that on certain point when the user scrolls down it turns into a relative element so it's not a sticky element anymore, only when the user scrolls to the top and passes over an specific element it turns again into a fixed/sticky element.
function Sticky($el){
this.$el = $el;
thi... |
I wrote a Pandoc filter that allows me to embed arbitrary HTML snippets in LaTeX documents, which are then printed out as-is when the document is converted to HTML. It is slightly more generic than it needs to be right now, in case I want to embed other types of things in the future.
It can be used like:
\begin{verbati... |
This is an implementation of ntohl() that I wrote as an exercise. ntohl() takes a uint32_t value and returns it unchanged if the host architecture is network-byte-order (big-endian), otherwise the value is converted to host-byte-order.
My version converts to little-endian; is it always the case that host-byte-order is ... |
I'm working on a small RestApi that would be able to:
Interpret different query languages like (...)/countries?where="..."&select="..." or (...)/GetCountries?ids="1,2,3"
Translate theses queries to SQL
Pass the SQL command to dapper and return the result
Note this API will be used by other services and that it won't... |
(Initial discussion from Classic merge sort, since it is new code, I start a new thread)
Post my code below, my major question is, I have to create another array result to hold sub-parts merge sort result. Is there a way I can just use original number to save additional space in result?
Any other comments on code bugs,... |
I'm creating a responsive page with bootstrap. I tested my code with my browser (Firefox and Chrome) and it works. Is the code clean or is there a better way to code it?
<div class="col-xs-12 col-sm-6 col-md-4" style="margin-top: 2%;">
<div class="adress">
<ul style="list-style: none; padding-left: 0">
... |
Given a serialized hash of any depth in string format, convert it into a hash object.
I want to know if my approach is correct, I am capturing states and storing the results in a stack and generating the hash from the stack. Also, is there a name for this kind of parsing approach?
def deserialize(input)
h = {}
l ... |
I've written a TicTacToe game using classes, just for learning purposes...
and I wonder If this code can be improved.
main.cpp
#include <iostream>
#include "tictactoe.hpp"
using namespace std;
int main(){
Tictactoe game;
game.intro();
return 0;
}
tictactoe.hpp
#ifndef tictactoe_hpp
#define tictactoe_hpp... |
export function addition(a: number, b: number) {
return a + b;
}
export function subtraction(a: number, b: number) {
return a - b;
}
The code is the same except the operator. Is it possible to avoid code duplication in such cases?
|
I'm new to C++ programming. I'm experienced in Java and its OOP paradigm.
This code works well. I just need to make sure whether it's correct in terms of C++ programming standard.
main.cpp
#include <iostream>
#include "ListNode.h"
#include "LinkedList.h"
using namespace std;
int main(void) {
LinkedList l;
Li... |
export function operator(a: number, b: number, operator: string, type: string): string | number {
switch (operator) {
case 'add':
if (type == "answer") {
return a + b;
} else if (type == "assignment") {
return a.toString() + " + " + b.toString();
... |
For classifying error reports, I need to generate an ID from an exception. That ID should be
(more or less) unique
a short alpha numeric string
equal for equivalent exceptions (even on different systems)
The following code seems to do the job:
public static string GetExceptionID(this Exception ex)
{
i... |
So,basically I am working on an algorithm for circular shifting a string upto a position.There are two parameters required here.
String of text to shift
Number of shifts required.
For example:
Given string: "Hello"
Shifts: 3
Final: "ollHe"
Ignore the limited validation here.
import java.lang.*;
import java.util.*;
... |
I am using Laravel 5.3, and currently working on models.
I have the following code:
$result = TheEpisode::find($id)->with('TheParts')->take(1)->get()->each(function ($item) {
$item->TheParts->makeHidden("title");
});
The purpose of this code is to display all the data from TheEpisode and TheParts, but exclude th... |
Background
I have decided to use this year's Advent Of Code to learn Haskell. I feel like I vaguely understand the language and can solve most of the problems with relative ease. However, the code I produce is not the most readable and possibly has inefficiencies. Any suggestions on how to improve readability and perfo... |
I am looking for a review of my perfect TicTacToe algorithm. It will be split up into 3 parts:
The function
The GameState Class
The game (NOT well designed)
I am mainly looking for tips and comments on the first 2, but I will take comments / tips on the poorly designed game.
alphabeta.py
#Using wikipedia pseudocode w... |
Wondering if there is anything I can improve upon my code?
This method accepts a filename (usually will be the path to the file in txt format), the starting row count of that file and the total amount of rows of the file. The method is suppose to iterate through the starting row count passed in and then write into a ne... |
I wrote this hangman program. It takes three words in an array, picks a random word and then the user guesses the letters. It's lengthy, but it's extremely simple and understandable. Suggestions are welcome, but keep in mind, my knowledge in java is limited.
import java.util.*;
public class Hangman
{
public static ... |
package com.goman;
public class BST {
private BST left;
private BST right;
private int data;
public BST(int data, BST left, BST right){
this.left = left;
this.right = right;
this.data = data;
}
public BST insert(BST node, BST root){
if(root == null){
... |
Based on a set of globs contained in a custom field within a package.json file, I'm trying to get a list of all the files that the glob matches. In my continual quest to get more familiar with Bluebird, I've chosen to use it to facilitate this task. What I have works, but I'm not sure if I am using the methods as inten... |
I wrote the following as more of an experiment than anything else, but I thought it would be fun to share and maybe get some feedback!
Motivation: I started looking at some functional languages and noticed how useful the |> pipeline operator is. I started wondering how it might be translated to the Java language.
There... |
I am using this code in a worksheet to check the condition, and based on the condition, copying the entire row of values in a different range of particular condition if true.
For copying I am clearing the destination range each time and copying the same data with updated information on the same destination. This makes ... |
I think this code is only simple math, but I'm posting it, because almost everyone fakes the scaling with unparenting, then parenting again.
Vector3 originalParentScale = new Vector3;
Vector3 originalScale = new Vector3;
void Awake(){
originalScale = transform.localScale;
originalParentScale = transform.parent.... |
I wrote this a while ago but wanted to see if I went about it the right way and if my brain is working correctly. I was thinking about these two projects the other day and I recently released the source. This game was originally for a Windows Form Game Jam so you have full context.
This code worked but I always felt th... |
I made a primality tester with trial division. I'm trying to make it as fast as possible and have reached the point now where I'm out of ideas.
I use the generator approach and not lists because I found out that it's awfully slow to generate and checklists for big ranges.
Does someone have ideas on how to improve the i... |
I'm new to Python, and my first serious project was a FreeCell game. The game works, with lots of options to combine moves, save games, load them, etc. But I skimped on some specifics of Python. In particular, reading in options.
import re
vertical = False
doubles = False
autoReshuf = False
savePosition = False
saveOn... |
I tried hard to come up with a function template computing a sliding average. A sliding average over data \$x_1, x_2, \dots, x_n\$ with window length \$k \leq n\$ is a sequence \$y_1, y_2, \dots, y_{n - k + 1}\$, where
$$y_i = \frac{1}{k}\sum_{j = 0}^{k - 1} x_{i + j}.$$
Here is my attempt:
mymath.h
#ifndef MYMATH_H
#d... |
I have a ThreadPool class which has grown to a point where it is becoming difficult to keep all of this unit of work in mind. It is also becoming harder to read. For this reason I would like to break this class into component classes.
First of all here is the class header with comments:
//ThreadPool.h
#ifndef THREADPO... |
I am implementing the logic for a Checkers game in F#. I am writing my code in a library so it can be called from any UI provider, and am trying to do it in good FP style. I currently have the following code; each file is provided in the order of compilation:
Checkers.fs This contains some unions and records that wil... |
What do you think about this simple calculator?
while True:
print('Options:')
print('Enter \'a\' to add two numbers')
print('Enter \'s\' to subtract two numbers')
print('Enter \'m\' to multiply two numbers')
print('Enter \'d\' to divide two numbers')
print('Enter \'q\' to quit the program')
... |
I'm doing this HackerRank problem:
Consider two sets of positive integers, \$A=\{a_0, a_1, \ldots, a_{n-1}\}\$ and \$B=\{b_0, b_1, \ldots, b_{m-1}\}\$. We say that a positive integer, \$x\$, is between sets \$A\$ and \$B\$ if the following conditions are satisfied:
All elements in \$A\$ are factors of \$x\$.
\$x\$ is... |
I want to make a method arrayIntPush(3, {5,4,8}) that will return {5,4,8,3}.
This method seems to work:
public static int[] arrayIntPush(int item, int[] oldArray) {
int len = oldArray.length;
int[] newArray = (int[]) Array.newInstance(oldArray.getClass().getComponentType(), len + 1);
System.arraycopy(oldArr... |
I am a self - taught coder, and have been learning Java for the last 2 years.
I have recently created a tic tac toe game in Java. I have rearranged the program into separate classes & methods. I am skeptical of how object-oriented my program is.
I don't really want help on how to make the game better in visuals or any... |
I need advice for this implementation that I made for a service access portable class library referenced to Xamarin.Android and Xamarin.Ios projects. For now, it works fine, but I have doubts about its performance or if it would crash on simultaneous calls.
public class HttpClientBase : HttpClient
{
private static... |
As a complete beginner, I didn't care about how the code looked as long as it works. However, now I am starting to think about how to make code be more maintainable and easier to read.
I feel I have too many else ifs in the following code. I invite you to give me constructive criticism and suggestions.
The purpose of t... |
I've got a PR to add a feature to a Ruby application (Puppet) to allow Regex detection.
Right now, the method only does comparison on exact string matching:
defaultfor :operatingsystem => :fedora, :operatingsystemmajrelease => ['22', '23', '24']
This is annoying, as we have to add in new values everytime a new Fedor... |
I've written my own implementation of strcat in C.
char* my_strcat(char *str1, char *str2)
{
int len_str1 = 0, len_str2 = 0, len_str3;
for (int i = 0; str1[i] !='\0'; i++)
{
len_str1++;
}
for (int i = 0; str2[i] != '\0'; i++)
{
len_str2++;
}
len_str3 = len_str1 + len_str2;
cha... |
I have this procedure to realise a find and replace on a word document. Since I have text boxes, using this way to do this is a bit a slower than what I'd like it to be, if it were just text on a plain doc document or tables and using just:
Document.Content.Find.Execute(FindText:=Find, MatchWholeWord:=True, ReplaceWit... |
Here goes my first stack implementation with go
New to the go language and it's been ages since I implemented a stack
Would love to discuss the data structure implementation itself and how "goish" the code looks.
package stack
import "errors"
var (
errEmptyStack = errors.New("Stack is empty")
)
type node struct ... |
Recently, I was given a math assignment to calculate Gini Indexes for a table of percent distributions of aggregate income.
The table takes the form of:
Year 1st Quintile 2nd Quintile 3rd Quintile 4th Quintile 5th Quintile
---- ------------ ------------ ------------ ------------ ----------... |
I'm trying to solve the following Advent of Code problem in F# for practice.
Description of problem (can be found here):
Basically, there's a 'key pad' that I need to figure the combination to. To do that, I have to follow instructions in the form 'U'/'D'/'L'/'R' to move a key up, down, left, or right in a gird of key... |
I wanted to write something that would find all pyramid words within a supplied text file or list of strings. An example of a pyramid word is the word "deadheaded". It has one of the letter "h", two of "a", three of "e", and four of "d".
This would form a pyramid if you were to stack the letters:
h
a a
e e e
... |
I'm working on this valid palindrome problem. Any advice on code bug, better idea for low algorithm execution time complexity, code style, etc. are highly appreciated.
Problem
Given a string, determine if it is a palindrome, considering only
alphanumeric characters and ignoring cases.
Example
"A man, a plan, a canal... |
I have the following piece of Perl script for updating an Oracle database. It's working perfectly fine, but I want to know how I can simplify this script.
use DBI;
my $dbh;
my $bad_form = "text.txt";
open (OUT, $bad_form) or die "Could not open $bad_form";
while (<OUT>){
chomp $_;
my ($item_id, $description, $fo... |
I have written a solution to find the occurrence of a common number in a n lists. I am just concerned if this is the best solution? Please suggest the best way to do it.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CommonNumberFinder
{
final static List<Number> list1 ... |
I am currently writing a small configuration API for myself, i want to use it to easily read/write to a file, however, i want to make sure it's efficient and get some other options into the field of my programming. How can i make my classes even more efficient?
This is the class for the options for comments, headers an... |
This is a scenario where we keep a single instance(as in Singleton Pattern) to get the configuration of an application.
Below is the main class and i set values to the configuarion values here and call the methods of the other classes to check if they are getting the correct values.
public class A{
public static vo... |
Aim: randomly generate \$n\$ numbers between \$a\$ and \$b\$ with (roughly) mean \$m\$.
Problem: The simple beginner's code I wrote becomes very inefficient as \$m\$ moves away from \$\frac{a + b}{2}\$.
import random
import numpy as np
import time
low = 0
high = 100
data = 50
def lst_w_mean(target):
HT = [x for ... |
I created a really basic game class. A game has GameObject instances, which currently have a position only.
This code is running on the client, and in each loop iteration:
The client receives the updates from the server
It executes the received events
The client updates the game state
I created a map to store game ob... |
I have started doing Kattis challenges from their website. For now I am still at the low complexity ones.
The first line of input contains a single positive integer T≤50 indicating the number of test cases. The first line of each test case also contains a single positive integer n indicating the number of elements av... |
I recently applied for a job as a Python coder but was rejected.
This was the problem:
Write a python code to check if an array has a sequence (1,3,4)
Assuming they were looking for expert Python programmers, what could I have done better?
# Tested with Python 2.7
import unittest
# Runtime: O(n)
def doesSeqAppear(i... |
I am trying to code a thin wrapper around the OpenGL so I can use it more convenient. This class is not 100% done yet, but I don't want to do all typing for nothing. And I think the design is clear. I would hope some review anything they see with my C++ code or with the way I use OpenGL.
.hpp file
#pragma once
#includ... |
The algorithm should be checking if the block fits perfectly when it falls.
The block is always the same shape:
.##....
..##....
Keep in mind I wrote this in 1 hour - all the time we had for the task. How can I make it more optimized?
#include <stdio.h>
#include <stdlib.h>
int check(char *k, int r, int s){
in... |
Can someone please go through this?
#include <iostream>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <set>
#include <cmath>
#include <cstring>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <stdlib.h>
#include <vecto... |
def check_rule(token, training_data, mode):
if mode == "frag":
children = training_data["words"]
remove = list.remove
def in_child(x):
for i in token:
if i not in x:
return False
remove(x, i)
return True
for... |
The following method is used to keep a DataContext open if it is closed or broken and is called before most calls to access the database.
It runs in a service that needs constant access to the database, constantly opening and closing the connection would be too costly. So we only reconnect if the connection has been cl... |
So I have this array of objects, which respectively contain other objects:
const template_columns = [
{
"id": 38,
"name": "Ideas",
"position": 0,
"template_id": 4,
"column_type": "Column",
"workflow": [
{
"action": "Next",
"move_to": "Backlog",
"assign_to": "none"... |
I am trying to create a simple Blackjack game. I am using GIST because the code sample takes forever to use.
Current code:
from random import randint
def card_deck():
#sets the card types and values
card_value = ['Ace','2','3','4','5','6','7','8','9','10','J','Q','K']
card_type = ['Hearts','Spades','Clubs',... |
I made code to shuffle an array in a semi-random way. That is, it has to be random based on a string, but for the same string, it should return the same order.
Is there a better way of doing it?
function djbHash(s) {
let hash = 5381;
for (let c of s) {
hash = hash * 33 + c.charCodeAt(0);
}
retu... |
I have a little code that draws a triangle wave:
package work3;
import javafx.application.Application;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Graphics;
import java.lang.Math;
impor... |
This is how I convert e.g. RGB(255, 0, 0) (where red is stored in the least significant byte of a Long) to a 6-digit hex string FF0000:
Function RgbToHex(l As Long) As String
Dim r As Long
Dim g As Long
Dim b As Long
r = l And ColorConstants.vbRed
g = (l And ColorConstants.vbGreen) / (2 ^ 8)
b = (l And Colo... |
This is part of my kynnaugh-cc TeamSpeak 3 plugin implementing speech recognition for deaf/hearing-impaired users. One of the self-contained classes in my code has the job of converting incoming PCM samples from TeamSpeak into FLAC format for transmission to the Google Cloud Speech API. The Cloud Speech API only accept... |
The code is working perfectly. I'm little bit sure this is a packet what I am sending from client to server in streams. Is this packet? Am I sending in a right way?
Another thing is that I am sending ACK from server to client. Is this right way to send ACK and NACK? Moreover, I am parsing on client side the ACK and che... |
I'm working on a function that reduces pairs of elements if they meet some criteria.
For example, given an array: ["1", "2", "a", "b", "3", "4"] I want to transform it so that strings that represent numbers are combined with addition, and strings that represent letters are concatenated so the output would be: ["3" "ab"... |
I have the following assignment:
A program that takes four (4) inputs then using a conditional
statement does the following:
Display the values that are below or equal to 25.
Multiply the values that are below 20 with each other.
Add the values that are above 25 with each other.
I've successfully solved all of th... |
I'm new at this and I'm almost done with learning basic Java. I made this just to see if I could do it. I just want to know if there's anything I can do to make it better.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static java.lang.Double.*;
class Calculator {
private JFrame frame = n... |
I have been learning about the rule of five and I tried to implement an example myself. It all works exactly as I'd expect, but I was wondering if I've missed any obvious issues or easier/faster ways of implementing the constructors and operators.
class string {
public:
string() : data(nullptr) {
std::cout ... |
I was working on a CodeChef challenge: Our Base is Under Attack. I have a working solution but it is not fast enough. Could you recommend anything to make it faster?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
class BaseAt... |
I have this method in Java:
private static int ConvertToTimestamp(Date value)
{
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S", Locale.US);
String text = "1970-01-01 00:00:00.0";
LocalDateTime localDateTime = LocalDateTime.parse(text, formatter);
// getTime() returns ... |
I wrote this switch function for Python, as there isn't a built-in one and most of the Googlable ones doesn't execute code, but only return something (I admit I haven't looked much further than a single Stack Oveflow page to see what people use, but a lot of the solutions are unnecessarily complex):
def switch(variable... |
This is a very simple task, but I'm curious if there is a better, more 'Pythonic' way to solve this.
"""The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 552 = 3025
Hence the difference between the... |
I have this method which calculates the average, median and percentile information given a long array of numbers. Is there any better and efficient way to do the same?
public static double median(long[] numbers) {
Arrays.sort(numbers, 0, numbers.length);
int middle = numbers.length / 2;
if (numbers.length... |
This assignment requires obtaining the deviation and variance of \$n\$ numbers stored in one single array. Is there any way to make this code more efficient?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int arrSize = 14;
double average , sum = 0 , dev = 0;
double deviation[... |
I knew a little Java, and thought what the hell, I'll help my school and design this program that'll help checkout phone chargers and calculators and things to students. So I got in way over my head, but I got the program working. I wrote it in C#, and while the whole thing needs review, I really feel my checkout funct... |
I'm trying to show data in UITablleView after getting it from an HTTP request. I heard that the best and professional way to do it is configure the cell and do the call request in model class then send it to the view controller.
Here is what I tried to do, but I think it's not going well. I know this is a wrong way but... |
I have a basic JSON API written in PHP. I want to validate incoming JSON data.
I know there are PHP JSON validators out there, here is a quick one I just rolled up.
<?php
$json_payload = json_decode('{
"data": {
"a_string": "short",
"a_number": 7
}
}');
validateJSONPayload(
'{
"data": {
"a_st... |
I worked on implementing a simple moving average function in Rust, that works on a collection of year/revenue tuples:
fn compute_moving_average(window: &Box<&[(u32, u32)]>) -> (u32, f32) {
let window_size = window.len();
let current_year = window
.iter()
.nth((window_size as f32/ 2.0).floor() a... |
Working on below find first bad version problem, post my code in Python 2.7, any smarter ideas for better time complexity, any code bug or code style advice are highly appreciated. My major idea is divide and conquer like a binary search.
Problem,
You are a product manager and currently leading a team to develop a new ... |
I'm working on implementing a queue using a circular buffer problem. Any smarter ideas for better time complexity, any code bug or code style advice are highly appreciated.
class QueueOnCirciularBuffer:
def __init__(self, max_size):
self.buffer = [0]*max_size
self.index = 0 # element to write
... |
I have a c# application which displays the names of assessments and the zone which they are performed upon, separated by a comma and a space. For instance:
assessment1, Firewall
mom's assessment, LAN
When the user selects on of these assessments, I need to separate the assessment name from the zone name. I also need ... |
The problem statement (Codeforces#
385C) is this:
We are given a sequence of \$n\$ numbers, i.e. \$x_i\$ and \$m\$ queries to find how many of these are divisble by primes between two given numbers (not necessarily prime) \$l_i\$ and \$r_i\$ (inclusive).
Constraints are: \$1\le n\le 10^6, 2\le x_i \le 10^7, 2\le m \l... |
while doing a code clash on codingames, in which we had to replace a character in a string one by one to transform it into a target string, printing out every itteration of the new string, resulting in something like this:
"Turtle Ham"
"Hurtle Ham"
"Hartle Ham"
"Hamtle Ham"
"Ham le Ham"
"Ham Me Ham"
"Ham Ma Ham"
"Ham M... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.