/dpt/ - Daily Programming Thread

Previous thread : What are you working on, Jow Forums?

Attached: 1560734327463.gif (1012x996, 2.42M)

Other urls found in this thread:

wiki.haskell.org/GHC/Memory_Management
twitter.com/SFWRedditVideos

Mutable lists in Haskell
wiki.haskell.org/GHC/Memory_Management

Attached: haskell.png (1328x1768, 237K)

good thread

Lisp is the most powerful programming language.

kys weeb

fuck mathlets

please do not post lesbians in /dpt/

Today's /dpt/ programming challenge:

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

e.g
Input: [2,2,1]
Output: 1


Input: [4,1,2,1,2]
Output: 4


p.s. Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

what are we going to do when the lisp guy, the forth guy, and the js anime doll guy all die/stop posting here

Code takes up memory, so no, that's impossible.

#include
#include

template
int get_single(const std::vector& nums)
{
int single = nums[0];
int single_count = 1;

for (int num : nums) {
int current_count = 0;
for (int n : nums) {
if (num == n) {
current_count++;
}
}
if (current_count == single_count) {
single = num;
}
}
return single;
}

int main(void)
{
std::vector a = { 2, 2, 1 };
std::vector b = { 4, 1, 2, 1, 2 };

std::cout

you xor them

new challenge please
this has been done in prev thread

Based, Haskell is literally worse than Java in practice. Optimizing Haskell code is more brain damaging than reverse engineering monkey-generated code.

Attached: 1469074283255.png (504x664, 420K)

def only_once(lst):
ans = 0
for n in lst:
ans ^= n
return ans

is using auto instead of int in get_single the same thing?

what does kimori mean?

Attached: 1545416224504.jpg (216x234, 8K)

...

Improved version

Attached: haskell.png (1328x1768, 328K)

It means GO FUCKING NECK YOURSELF YOU DISGUSTING ATTENTION WHORING ANIME PEDO SCUM DIE DIE DIE DIE DIE

yikes

Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".

e.g.
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first three athletes got the top three highest scores,
so they got "Gold Medal", "Silver Medal" and "Bronze Medal".
For the left two athletes, you just need to output their relative ranks
according to their scores.


p.s.
N is a positive integer and won't exceed 10,000.
All the scores of athletes are guaranteed to be unique.

yes. i just chose int because i know the array will contain ints.

Kimoi = disgusting, gross
い = i (left part is longer)
り = ri (right part is longer)

rude

Attached: 488606CC34344B4AA60BFFDED8649860.png (344x398, 189K)

You really missed 3 JavaScript lessons this week? You're unbelievable, Anone...

Attached: a968c089bf1c6682200d4a6398c1b61c.jpg (663x1065, 87K)

what kind of retarded challenge is that? sort an array?

is there a better solution than qsort?

var input = new [] { 5, 4, 3, 2, 1 };
var ranks = input.Select((x, i) =>
i == 0 ? "Gold medal" :
i == 1 ? "Silver medal" :
i == 2 ? "Bronze medal" :
(i + 1).ToString()
);
foreach (var rank in ranks)
Console.WriteLine(rank);

here you go bro
const arr = [4, 1, 1, 2, 2];
let solve = arr => arr.reduce((total, current) => total ^= current);
console.log(solve(arr));

JavaScript is piss easy. Why would I need lessons?

Rejoice.

const process = (accum, current) =>
accum.includes(current)
? accum.filter(x => x !== current)
: [...accum, current]

const challenge = input => {
const unique = input.reduce(process, [])
return unique[0]
}

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.

e.g.
Input: A = "ab", B = "ba"
Output: true


p.s.
Input: A = "ab", B = "ab"
Output: false


Input: A = "aa", B = "aa"
Output: true


p.s.
0

Here's to hoping Ada on LLVM will be released before 2020

thanks
>い = i (left part is longer)
>り = ri (right part is longer)
whoops rookie mistake

Attached: aa5e080e1f05b52ac2f58e480ddc31b1751fda73def4711c896c1a6108d44b89.png (652x716, 530K)

>let
>reassigning to the argument you are returning anyway
and this is why you need those lessons

SOMEBODY PLEASE RESPOND!!!!

Attached: 1541981991308.png (479x506, 281K)

Don't forget the Ada guy

thanks bb

too over engineered? nice anyway

I prefer code that is readable

better stay away from haskell then

It works the same way dynamic linking does, you depend on the kernel symbols and when you load your module, part of the loading process is to check if those symbols are present in the kernel.

i think you're trying too hard buddy

These immaculately groomed dolls cannot lead to anything good i'm sure.

SQL monkey here
WITH CTE (Score, Rank) AS (
SELECT Score, ROW_NUMBER() OVER (ORDER BY Score DESC)
FROM (VALUES
(5), (4), (3), (2), (1)
) AS A (Score)
)
SELECT CASE Rank
WHEN 1 THEN 'Gold medal'
WHEN 2 THEN 'Silver medal'
WHEN 3 THEN 'Bronze medal'
ELSE CAST(Rank AS VARCHAR) END AS Rank
FROM CTE

What do you mean?

write unnecessary complicated code

how well do you know your joins, outer joins, left, joins, etc?

Complicated? I think its quite easy to read...

About, three fiddy.

i use joins: inner and left mostly
seldom use right & outer

>abusing ASI
>abusing spread operator
>unnecessarily overengineered code
This is what FP and lisp does to your brain
muh cons and cadr
muh head and tail
lmao am smurt

#include
#include
#include

int main(void)
{
std::vector medals = { "Gold", "Silver", "Bronze" };
std::vector a = { 4, 5, 23, 4, 5, 0, 21, 22 };

std::sort(a.begin(), a.end(), std::greater());

for (auto& num : a) {
static int count = 0;

if (count < 3) {
std::cout

sqlite is good enough for 90% of DBA work. People go overboard in R&D phase and pick out software that is completely overkill.

no const on vectors?

Ok, I wrote it another way

const hasTwice = (array, item) => array.filter(x => x === item).length === 2

const challenge = input => {
const unique = input.filter(x => !isTwice(input, x))
return unique[0]
}

var input = new [] { 5, 4, 3, 2, 1 };
var ranks = input
.OrderByDescending(x => x)
.Select((x, i) =>
i == 0 ? "Gold medal" :
i == 1 ? "Silver medal" :
i == 2 ? "Bronze medal" :
(i + 1).ToString()
)
;
foreach (var rank in ranks)
Console.WriteLine(rank);

forgot to sort first

>you depend on the kernel symbols
that's where i'm confused i guess, what does the build process do find the kernel symbols if the module isn't built against the kernel?

What if I want more than one person to use my software.

Yeah, good luck with that.

lel

>that's where i'm confused i guess, what does the build process do find the kernel symbols if the module isn't built against the kernel?
I'm not sure what you mean. The symbols are defined in header files.
The actual checking against them isn't done until the module is being loaded.

In header files and in various symbol files, I mean. Look up how Modules.symvers works. You do "sort of" build against specific kernel, but it's dynamically linked.

alright, that makes sense.

is this what the process roughly looks like?
>module is built and symbols are referenced by name from the kernel headers
>kernel matches up these symbols to memory addresses when the module is loaded

I'm learning Haskell, and I've got a pretty good grip on the semantics of lazy evaluation, and its compiler implementation. However, I still have trouble reasoning about the efficiency of some code.
Namely, in the example:
isPalindrome xs = xs == reverse xs

as far as my understanding goes, that reverse will actually evaluate only on each (==) evaluation, and it will produce code equivalent to this C snippet:
for(int i = 0; i < n; i++)
if(str[i] != str[n-i])
return 0;
return 1;


Which would make it O(n), right? Also, how, and by how much, does the optimise flag on GHC affect code generation?

I see a lot of people here using built in functions to solve the programming challenges, is this frowned upon in technical interviews or are they generally okay with it? Obviously it's unnecessary to build a custom hashmap or arraylist when a lot of langs have built in ones, but I could see why someone might frown upon you using a built in quick sort or something like that.

Attached: 1517094039892.jpg (1920x1080, 512K)

>>module is built and symbols are referenced by name from the kernel headers
By name and arguments. The headers are really just used for compiling the code, and the Module.symvers and EXPORT_blablah magic stuff is the format used by the loader.

>kernel matches up these symbols to memory addresses when the module is loaded
Yes. You can actually see all the physical addresses of kernel symbols using /proc/kallsyms

usually in interviews they want you to write the OS your programming language is going to run on to solve the problem

Unless the solution is the same thing as the problem you can generally expect to get away with using standard utilities like hashes, sort functions and so on.

I see, thank you for explaining it. I'm still a little unclear on how all of these parts fit together, but now I probably have enough now to google the rest.

I am just getting started with linux kernel development, just finished task 1 by making a "hello world" kernel module and makefile, but wasn't sure how /lib/modules/.../build/Makefile actually built the module.

I've never really bothered looking in to how the building and loading actually works, I just invoke the kernel building system and it just sorta works for me. So my understanding of it, like you can probably tell from my posts, is quite superficial. I have a far better grasp on how the process loader works in userspace, after having implemented a linker for fun.

Sqlite works just fine with multiple writers and readers. Ever try it in WAL mode? The only downside to sqlite is that it locks the entire database during a transaction, but that's not going to be an issue unless your database is legitimately 20GB+ in size. Your commits should be blazing fast and you won't see much delay.

improved version
-module(p71769853v2).
-export([main/0]).

main() ->
run(true).

run(true) ->
List=[4,4,[999],[999],[999],abc,abc,j,j,8,"w",8,"w"],
io:format("Input: ~p~n", [List]),
[_,D]=second(splitlist(List)),
io:format("Output: ~p~n", [D]).

splitlist(List) ->
splitlist1(List).

splitlist1([]) -> [];
splitlist1(List) ->
[[X || X X /= lists:last(List) end, List)).

second(Splitlist) ->
lists:append([(case A /= 2 of true -> [A,B]; _ -> [] end) || [A,B]

third case is tricky. my code fails. if i check equality or count = 0, 2nd case doesn't fail. advice?
void Main()
{
var inputs = new [] {
new [] { "ab", "ba" },
new [] { "ab", "ab" },
new [] { "aa", "aa" }
};

foreach (var input in inputs)
Console.WriteLine(isSwapable(input[0], input[1]));
}

bool isSwapable(string a, string b)
{
if (a.Length != b.Length)
return false;

int count = 0, prev = -1, curr = -1;
for (var i = 0; i < a.Length; i++)
{
if (a[i] != b[i])
{
count++;
if (count > 2)
return false;
prev = curr;
curr = i;
}
}

return (count == 2 && a[prev] == b[curr] && a[curr] == b[prev]);
}

lazy sorting to get top 3 and solved in linear time

Good to know, I always feel iffy when using built in methods when solving leetcode.

I thought you were supposed to build a von neumann machine first from scrap metal?

>import external library
imports FizzBuzz
FizzBuzz()

that only happens in entry level jobs

#include
#include

using namespace std;

bool check(string a, string b)
{
swap(a[0], a[1]);
return (a == b) ? true : false;
}

int main(void)
{

string a = "ab";
string b = "ba";

string c = "aa";
string d = "aa";

cout

bro....
the strings can be bigger than 2 chars

I didn't think so. Are they always necessary?

did you read this part?
0

stupid challenge
def sort_athletes(lst):
return ["Gold Medal", "Silver Medal", "Bronze Medal"] + sorted(lst)[2:]


naive n^2 solution, will try to find something better
def check_swap(str1, str2):
for i, c in enumerate(str1[0:-1]):
for j, k in enumerate(str1[i+1:]):
if str1[0:i] + k + str1[i+1:j+i+1] + c + str1[j+i+2:] == str2:
return True
return False

based

2 chars is all a man needs

Attached: 1537488482041.jpg (395x401, 59K)

check this out

Attached: 1560148849719.webm (1280x720, 1.93M)

what if there're only 2 athletes?
who got the bronze medal?
a ghost athlete?

of course i read it. i only need to change the first two characters, as the challenge called.

there's no "first two characters" stated in the challenge

>change the first two
>first two
lmfao
where is that written?

then whoever organized the race is a failure

Or you just failed the interview.

Don't call us, we'll call you

this is what you get when you weed while coding

Attached: just_weed.jpg (500x562, 80K)

Ugly, but I think it works

const challenge = (s1, s2) => {

// Obvious
if (s1 === s2) return true

// Obvious
if (s1.length !== s2.length) return false

// Check dispair elements
let dispar = []

for (let i = 0; i < s1.length; i++) {
const c1 = s1[i];
const c2 = s1[i];

if (c1 !== c2) dispar.push(c1, c2)
}

// Too many disparities
if (dispar.length > 4) return false

// Basic situation
if (dispar.length === 4) return dispar[0] === dispar[3] && dispar[1] === dispar[2]
}

lulz

Input: A = "ab", B = "ab"
Output: false

that's correct per OP

tried it in js, returns true.
should return false

>if (s1 === s2) return true

it should return false. user's solution returns true