Re: Removing elements from dynamic arrays?

2022-04-04 Thread Salih Dincer via Digitalmars-d-learn

On Monday, 4 April 2022 at 23:15:30 UTC, Enjoys Math wrote:


```d
// remove an item from an array
template drop(T)
{
  T drop( inout T[] arr, T which )
  { 
int i;
T result;

for (i=0; i < arr.length; i++)
{
if (arr[i] == which)
{
result = arr[i];
break;
}
}

debug if ( which >= arr.length)
throw new Exception(str.format("Attempt to drop the %s 
of value %s from an array, but it was not found.", typeid(T), 
which));

}

for (; i < arr.length; i++)
{
arr[i] = arr[i + 1];
}
arr.length = arr.length - 1;

return result;
  }
}
```


I'm guessing you're doing this to learn and measure. You might be 
better off using the slicing method though. It's also possible to 
do it with a single loop:

```d
auto dropSlice(T)(T[] array, T which)
{
  T[] result;

  size_t i;  // old index
  foreach(index, element; array)
  {
if(element == which) {
  result ~= array[i..index]; // slice off
  i = index + 1;
}
  }

  return result ~ array[i..$];   // last slice
}

void main()
{
  char[] dizi = "abcdefdg".dup;

  dizi.dropSlice('d').writeln;
```
SDB@79


Re: Removing elements from dynamic arrays?

2022-04-04 Thread Ali Çehreli via Digitalmars-d-learn

On 4/4/22 16:15, Enjoys Math wrote:
> https://forum.dlang.org/post/eih04u$1463$1...@digitaldaemon.com

2006 is a long time ago. :)

> A version of the code that takes `T which` as a parameter instead of
> `int index`.
>
> ```
> // remove an item from an array
> template drop(T)
> {
>T drop( inout T[] arr, T which )

I bet 'inout' back then was the equivalent of 'ref' today.

Today, I would use remove():

  https://dlang.org/library/std/algorithm/mutation/remove.html

And where applicable, SwapStrategy.unstable should reduce the number of 
elements moved.


Ali



Re: Google Code Jam 2022

2022-04-04 Thread Siarhei Siamashka via Digitalmars-d-learn
A plot twist. I actually used Golang for submitting all my 
solutions in the qualification round:

https://codingcompetitions.withgoogle.com/codejam/submissions/00876ff1/0048a518

The reason is that right now I'm switching to Golang at work. And 
Code Jam tasks are a good practice to become more comfortable 
with new programming languages, considering that the 
qualification round had no strict time limit. It's also a good 
chance to compare Golang vs. Dlang for this kind of activity.


Below are a few solutions for the second task of the 
qualification round "3D Printing": 
https://codingcompetitions.withgoogle.com/codejam/round/00876ff1/00a4672b


Golang:
```Go
package main

import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, 
a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, 
a...) }


// From 
https://stackoverflow.com/questions/27516387/what-is-the-correct-way-to-find-the-min-between-two-integers-in-go

func MinOf(vars ...int) int {
min := vars[0]
for _, i := range vars {
if min > i {
min = i
}
}
return min
}

// From 
https://stackoverflow.com/questions/37532255/one-liner-to-transform-int-into-string

func SplitToString(a []int, sep string) string {
if len(a) == 0 {
return ""
}
b := make([]string, len(a))
for i, v := range a {
b[i] = strconv.Itoa(v)
}
return strings.Join(b, sep)
}

func main() {
defer writer.Flush()
var t int
scanf("%d\n", )
for casenum := 1; casenum <= t; casenum++ {
var p1 = make([]int, 4)
var p2 = make([]int, 4)
var p3 = make([]int, 4)
var ans = make([]int, 4)
scanf("%d %d %d %d\n", [0], [1], [2], [3])
scanf("%d %d %d %d\n", [0], [1], [2], [3])
scanf("%d %d %d %d\n", [0], [1], [2], [3])
todo := 100
for i := 0; i < 4; i++ {
ans[i] = MinOf(p1[i], p2[i], p3[i], todo)
todo -= ans[i]
}
if todo > 0 {
printf("Case #%d: IMPOSSIBLE\n", casenum)
} else {
printf("Case #%d: %s\n", casenum, SplitToString(ans, " 
"))
}
}
}
```

Ruby or Crystal:
```Ruby
1.upto(gets.to_s.to_i) do |casenum|
  todo = 100
  a = 3.times.map { gets.to_s.split.map {|x| x.to_i } 
}.to_a.transpose.map do |x|

todo -= (result = [todo, x.min].min)
result
  end
  printf("Case #%d: %s\n", casenum, todo > 0 ? "IMPOSSIBLE" : 
a.join(" "))

end
```

Dlang:
```D
import std.algorithm, std.stdio, std.string, std.conv, std.range;

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
auto todo = 100;
auto a = zip(readln.splitter.map!(to!int),
 readln.splitter.map!(to!int),
 
readln.splitter.map!(to!int)).map!"a[].min".array;

foreach (ref x ; a)
  todo -= (x = min(todo, x));

if (todo > 0)
  writefln("Case #%d: IMPOSSIBLE", casenum);
else
  writefln("Case #%d: %(%s %)", casenum, a);
  }
}
```

Now which of these solutions is better? Getting a solution ready 
as fast as possible is usually very important in programming 
competitions, so expressive programming languages and smaller 
source code size is a clear advantage. That's why normally my 
primary choice would be Dlang (because Crystal is not supported 
by Code Jam, Codeforces and Codechef platforms at the moment).


But Golang is a simple language with no advanced features and 
syntax sugar, so it's easier for beginners to read and understand 
the code. From the practical point of view this is also useful 
and may be sometimes preferable in real projects. Python is 
easier than Ruby and is more popular. Golang is easier than Dlang 
and is more popular too.


I'm going to switch back to Dlang in the upcoming Round 1.


Removing elements from dynamic arrays?

2022-04-04 Thread Enjoys Math via Digitalmars-d-learn

https://forum.dlang.org/post/eih04u$1463$1...@digitaldaemon.com

A version of the code that takes `T which` as a parameter instead 
of `int index`.


```
// remove an item from an array
template drop(T)
{
  T drop( inout T[] arr, T which )
  { 
int i;
T result;

for (i=0; i < arr.length; i++)
{
if (arr[i] == which)
{
result = arr[i];
break;
}
}

debug if ( which >= arr.length)
throw new Exception(str.format("Attempt to drop the %s of 
value %s from an array, but it was not found.", typeid(T), 
which));

}

for (; i < arr.length; i++)
{
arr[i] = arr[i + 1];
}
arr.length = arr.length - 1;

return result;
  }
}
```

It has worse case complexity O(2n) = O(n) whereas the other one 
can run in half as long minimally and sometimes just as long (but 
still O(n)), but usually one needs to linear search for the entry 
first.


How do you get passed `LNK: cannot find python39.lib` errors when using PyD for Python to D calling?

2022-04-04 Thread Enjoys Math via Digitalmars-d-learn



```
C:\Users\FruitfulApproach\Desktop\BananaCats\BananaCatsInD\pyd\infrastructure\pyd\make_object.d(1190):
 Deprecation: returning `` escapes a reference to parameter `this`
C:\Users\FruitfulApproach\Desktop\BananaCats\BananaCatsInD\pyd\infrastructure\pyd\make_object.d(1190):
perhaps annotate the parameter with `return`
travis_fold:end:pyd_compile-24d8b1b1-b462-11ec-a868-3417eb9e56b5
library_dirs: ['C:\\Python39\\libs', 
'C:\\Python39\\PCbuild\\amd64']

runtime_library_dirs: []
libraries: ['python39']
travis_fold:start:pyd_link-259ac93e-b462-11ec-ab18-3417eb9e56b5
C:\D\dmd-2.096.1\windows\bin64\dmd.exe -m64 -debug 
-ofbuild\lib.win-amd64-3.9\hello_world.cp39-win_amd64.pyd 
build\temp.win-amd64-3.9\Release\infra\temp.obj 
-L/LIBPATH:\"C:\Python39\libs\" 
-L/LIBPATH:\"C:\Python39\PCbuild\amd64\" python39.lib 
build\temp.win-amd64-3.9\Release\infra\python_dll_def.def

LINK : fatal error LNK1104: cannot open file 'python39.lib'
Error: linker exited with status 1104
travis_fold:end:pyd_link-259ac93e-b462-11ec-ab18-3417eb9e56b5
error: command 'C:\\D\\dmd-2.096.1\\windows\\bin64\\dmd.exe' 
failed with exit code 1

```

I'm following the instructions here:
https://pyd.readthedocs.io/en/latest/extend.html#basics

And here:
https://pyd.readthedocs.io/en/latest/dub.html

But I haven't tried making a project with dub yet.  I just tried 
running the env vars-setting .bat file (second link) on 
`setup.py` and also my `main.py` and then running `python 
setup.py install`, which produces the above error.


Re: Const Variables

2022-04-04 Thread Ali Çehreli via Digitalmars-d-learn

On 4/4/22 13:37, H. S. Teoh wrote:

>> I remember reading somewhat similar requests in the past: Assign to a
>> variable freely but at some point say "no more mutation to this
>> variable".
> [...]
>
> It's not just "assign freely"; it's "assign once". Or rather, "assign
> before the outside world sees it".

I understand. I just remembered somewhat related other requests.

> In fact, now that I think of it, I wonder if this could actually be
> implementable in the current language.

I am not surprised. :)

Ali



Re: Const Variables

2022-04-04 Thread H. S. Teoh via Digitalmars-d-learn
On Mon, Apr 04, 2022 at 11:20:31AM -0700, Ali Çehreli via Digitalmars-d-learn 
wrote:
> On 4/3/22 17:42, H. S. Teoh wrote:
> 
> > In some sense, this is like an extension of ctors initializing
> > immutable values. The compiler tracks whether the variable has been
> > initialized yet, and inside the ctor you can assign to immutable
> > because the uninitialized value is not observable from outside
> > before that. Once assigned, the compiler enforces no subsequent
> > changes.
> 
> These ideas make sense to me.
> 
> I remember reading somewhat similar requests in the past: Assign to a
> variable freely but at some point say "no more mutation to this
> variable".
[...]

It's not just "assign freely"; it's "assign once". Or rather, "assign
before the outside world sees it".

In fact, now that I think of it, I wonder if this could actually be
implementable in the current language. Here's a first stab at it:

struct LazyValue(T) {
private class Impl
{
immutable T value;
this(immutable T v) { value = v; }
}
private Impl impl;
private T delegate() pure generate;

this(T delegate() pure _generate)
{
generate = _generate;
}

immutable(T) get() {
if (impl is null)
impl = new Impl(generate());
return impl.value;
}
alias get this;
}

void main() {
import std;
auto lazyInt = LazyValue!int({ return 123; });
writeln(lazyInt.get);
}

Currently generate() has to be pure, which limits the utility somewhat
(you couldn't load the value from a file, say).  But in principle, the
approach seems to work.


T

-- 
Obviously, some things aren't very obvious.


Re: Const Variables

2022-04-04 Thread Ali Çehreli via Digitalmars-d-learn

On 4/3/22 17:42, H. S. Teoh wrote:

> In some sense, this is like an extension of ctors initializing immutable
> values. The compiler tracks whether the variable has been initialized
> yet, and inside the ctor you can assign to immutable because the
> uninitialized value is not observable from outside before that. Once
> assigned, the compiler enforces no subsequent changes.

These ideas make sense to me.

I remember reading somewhat similar requests in the past: Assign to a 
variable freely but at some point say "no more mutation to this variable".


Ali



Re: I want to append to lists without using append

2022-04-04 Thread Vinod K Chandran via Digitalmars-d-learn
On Monday, 4 April 2022 at 13:32:19 UTC, Steven Schveighoffer 
wrote:


This looks more like lisp or scheme. You know this is a forum 
for the D programming language?



This was the same question in my mind.




Re: I want to append to lists without using append

2022-04-04 Thread Paul Backus via Digitalmars-d-learn

On Monday, 4 April 2022 at 12:57:28 UTC, V3nom wrote:

define the lists:

(define liste (cons 10(cons 20(cons 30(cons 40 ' ())
(define liste2 (cons 20(cons 30(cons 10(cons 40 ' ())


define the "function":

(define (listapp list1 list2)(
 if (null? (cdr list1))
(cons (car list1) (listapp list2 (cdr list1)))
  (if (null? (cdr list2))
  (cons (car list2) (cdr list2))
(cons (car list1) (listapp (cdr list1)  list2))
  )))

append them:

(listapp liste liste2)

What do i do wrong? i think this should work but it is giving 
me an error message like:mcdr: contract violation expected: 
mpair? given: ()


In this line:

if (null? (cdr list1))

...it is possible for list1 itself to be null. If that happens, 
the call to cdr will fail with an error. Before calling car or 
cdr on a list, you must first check to see if the list is null.


Your code contains several other instances of the same error. 
I'll let you find them on your own. :)


Re: I want to append to lists without using append

2022-04-04 Thread Steven Schveighoffer via Digitalmars-d-learn

On 4/4/22 8:57 AM, V3nom wrote:

define the lists:

(define liste (cons 10(cons 20(cons 30(cons 40 ' ())
(define liste2 (cons 20(cons 30(cons 10(cons 40 ' ())


This looks more like lisp or scheme. You know this is a forum for the D 
programming language?


-Steve


I want to append to lists without using append

2022-04-04 Thread V3nom via Digitalmars-d-learn

define the lists:

(define liste (cons 10(cons 20(cons 30(cons 40 ' ())
(define liste2 (cons 20(cons 30(cons 10(cons 40 ' ())


define the "function":

(define (listapp list1 list2)(
 if (null? (cdr list1))
(cons (car list1) (listapp list2 (cdr list1)))
  (if (null? (cdr list2))
  (cons (car list2) (cdr list2))
(cons (car list1) (listapp (cdr list1)  list2))
  )))

append them:

(listapp liste liste2)

What do i do wrong? i think this should work but it is giving me 
an error message like:mcdr: contract violation expected: mpair? 
given: ()



Thanks for helping me :)

Greetings


Re: Is it safe to read to memory after it has been allocated with `pureMalloc` and `pureRealloc`?

2022-04-04 Thread rempas via Digitalmars-d-learn

On Monday, 4 April 2022 at 09:26:13 UTC, Stanislav Blinov wrote:
No. Neither `malloc` nor `realloc` (for which D's `pure...` 
variants are mere wrappers) are specified to initialize 
allocated memory. `calloc`, however, is - it initializes 
allocated block with zeroes.


Thanks, that's what I was looking for! I'll switch to `calloc` 
instead. Have a great day!


Re: Is it safe to read to memory after it has been allocated with `pureMalloc` and `pureRealloc`?

2022-04-04 Thread Salih Dincer via Digitalmars-d-learn

On Monday, 4 April 2022 at 07:48:40 UTC, rempas wrote:


Maybe, I didn't explained it properly. The example works. 
However, I wonder if it randomly works or if it is safe to do 
something like that as if the bytes have been initialized to 
'\0'.


```d
import core.memory : pureMalloc;
import core.stdc.stdio : printf;

//extern (C)
void main()
{
  int limit = 23;
  auto str = cast(char*)pureMalloc(limit);

  //while (limit--) str[limit] = '\0';
  // You need this initialize ---^
  str[0] = 'J';
  str[1] = 'o';
  str[2] = 'h';
  str[3] = 'n';

  printf("My name is: %s\n", str);
  // Wrong Output: "My name is: John�U"
}
```

I found no problems when using ```extern()```. But it doesn't 
inspire confidence.  There is obviously a memory conflict when it 
removes ```while()``` loop and does not use ```ekstern()```.


SDB@79



Re: Is it safe to read to memory after it has been allocated with `pureMalloc` and `pureRealloc`?

2022-04-04 Thread Stanislav Blinov via Digitalmars-d-learn

On Monday, 4 April 2022 at 07:32:00 UTC, rempas wrote:
In other terms, do these functions auto-initialize memory to be 
ready for use?


No. Neither `malloc` nor `realloc` (for which D's `pure...` 
variants are mere wrappers) are specified to initialize allocated 
memory. `calloc`, however, is - it initializes allocated block 
with zeroes.


Re: Is it safe to read to memory after it has been allocated with `pureMalloc` and `pureRealloc`?

2022-04-04 Thread rempas via Digitalmars-d-learn

On Monday, 4 April 2022 at 07:39:08 UTC, Salih Dincer wrote:

On Monday, 4 April 2022 at 07:32:00 UTC, rempas wrote:


Does anyone knows what's going on here?


Source code?


Why does it matter?

```
import core.memory;
import core.stdc.stdio;
import core.stdc.stdlib;

extern (C) void main() {
  char* str = cast(char*)pureMalloc(23);
  str[0] = 'J';
  str[1] = 'o';
  str[2] = 'h';
  str[3] = 'n';

  printf("My name is: %s\n", str);
  exit(0);
}
```

Maybe, I didn't explained it properly. The example works. 
However, I wonder if it randomly works or if it is safe to do 
something like that as if the bytes have been initialized to '\0'.


Re: Is it safe to read to memory after it has been allocated with `pureMalloc` and `pureRealloc`?

2022-04-04 Thread Salih Dincer via Digitalmars-d-learn

On Monday, 4 April 2022 at 07:32:00 UTC, rempas wrote:


Does anyone knows what's going on here?


Source code?



Is it safe to read to memory after it has been allocated with `pureMalloc` and `pureRealloc`?

2022-04-04 Thread rempas via Digitalmars-d-learn
In other terms, do these functions auto-initialize memory to be 
ready for use? I test it out using `printf` to print a string. 
"%s" expects for a null terminated string and it seems to work so 
I suppose that these functions auto-initialize the bytes to `\0`.


However, memory is tricky and I still don't know how memory (and 
virtual memory) works under the hood so it may just randomly work 
and it may give me a segmentation fault at some point.


Does anyone knows what's going on here?