I found this code which does exactly what I want: gets a list of integers, and generates every combination.
perm([H|T], Perm) :-
perm(T, SP),
insert(H, SP, Perm).
perm([], []).
insert(X, T, [X|T]).
insert(X, [H|T], [H|NT]) :-
insert(X, T, NT).
Now what I want to do is, if one permutation does not meet some criteria, I want perm to return another result. So, and sorry for the lack of vocabulary, I want the same effect that would happen if I would execute that code, got a solution, and typed ; to get more results. I believe this is a very simple idea but I can't see it right now.
So, pseudocode would be:
enumerate(inputList, outputNodes, OutputArcs) :-
perm(inputList,OutputPermutation),
getArcs(OutputPermutation,OutputArcs),%I want to build the OutputArcs, then check for every element to be unique, if it isn't, generate another list with perm, if it IS, return said list as accepted)
areArcsNumberUniques(OutputArcs,OutputArcs),%TODO now is when I do not know how to make the call, here if it is valid, end, if it isn't, call perm again)
So I would need to understand how do I go about this. Also, any other ideas about the problem are welcome, since I'm brute forcing my way because I'm unable to find any type of algorithm or pattern to solve the actual problem (which I've asked about before. This is my attempted solution, just in order to give an actual answer to the exercise...)
edit: query:
enumerate([a-b,b-c], EnumNodos, EnumArcos).
expected output:
EnumNodos = [enum(3,a), enum(1,b), enum(2,c)],
EnumArcos = [enum(2,a‐b), enum(1,b‐c)]
This would be like the end game goal, where I get a list of arcs where each arc has an unique value that is equal to substracting the values of its nodes (every node also has an unique value).
And so far, since I did not find any way to do this algorithmically, I thought about trying every possibility (basically I cannot get an unique way to do this, trees with different branches seem different to me, and only restriction is that there are N nodes and N-1 arcs).
edit more examples:
6a
5 4
1b 2e
2 3
3c 5f
1
4d
EnumNodos = [enum(6,a), enum(1,b), enum(2,e), enum(3,c), enum(5,f), enum(4,d)],
EnumArcos = [enum(5,a‐b), enum(4,a-e), enum(3,e-f), , enum(2,b-c), enum(1,c-d)]
5a
4 3
1b 2e
1 2
3c 4f
EnumNodos = [enum(5,a), enum(1,b), enum(2,e), enum(3,c), enum(4,f)],
EnumArcos = [enum(4,a‐b), enum(3,a-e), enum(1,b-c), , enum(2,e-f)]
5a
4 3
1b 2e
2
3c
1
4d
9a
8 7
1b 2e
6 4
7c 6f
2 2
5d 4g
3 1
8h 3i
Related
I'm trying to compare two hex values as in the code at the bottom. I was expecting that the IF statement, where I compare field A and field WS-FLD-X, would result in true, but it doesn't do it.
In other words, when I move 12 to WS-FLD-A, the value in WS-FLD-X should be stored as X'0C', right? This value is expected to be the same value in field A. Comparing the two values should result in true, however this is not happening.
Why? What is the difference between the value held in field A and the value in WS-FLD-X?
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO-WORLD.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 FF.
05 A PIC XX.
05 B PIC XXXXXX.
01 F.
05 WS-FLD PIC S9(4) COMP.
05 WS-FLD-X REDEFINES WS-FLD PIC XX.
PROCEDURE DIVISION.
DISPLAY 'Hello, world' UPON CONSOLE.
MOVE X'0C' TO A.
MOVE "SOME TEXT" TO B.
DISPLAY FF UPON CONSOLE.
MOVE 12 TO WS-FLD
DISPLAY "HEX OF 12 IS:" WS-FLD-X UPON CONSOLE.
IF WS-FLD-X = A THEN DISPLAY "SAME" UPON CONSOLE END-IF.
Code in web IDE
You moved a single byte to a 2 byte field so the move padded to the right with a space (per Simon).
MOVE X'0C' TO A. // (A now contains x'0C20' which is not 12)
You'd need to move both bytes to keep the value of the number intact.
MOVE x'000C' TO A
The program now displays 'SAME'.
The problem: create a function with one input. Return the index of an array containing the fibonacci sequence (starting from 0) whose element matches the input to the function.
16 ~ │ def fib(n)
17 ~ │ return 0 if n == 0
18 │
19 ~ │ last = 0u128
20 ~ │ current = 1u128
21 │
22 ~ │ (n - 1).times do
23 ~ │ last, current = current, last + current
24 │ end
25 + │
26 + │ current
27 │ end
28 │
60 │ def usage
61 │ progname = String.new(ARGV_UNSAFE.value)
62 │
63 │ STDERR.puts <<-H
64 │ #{progname} <integer>
65 │ Given Fibonacci; determine which fib value would
66 │ exist at <integer> index.
67 │ H
68 │
69 │ exit 1
70 │ end
71 │
72 │ if ARGV.empty?
73 │ usage
74 │ end
75 │
76 │ begin
77 ~ │ i = ARGV[0].to_i
78 ~ │ puts fib i
79 │ rescue e
80 │ STDERR.puts e
81 │ usage
82 │ end
My solution to the problem is in no way elegant and I did it at 2AM when I was quite tired. So I'm not looking for a more elegant solution. What I am curious about is that if I run the resultant application with an input larger than 45 then I'm presented with Arithmetic overflow. I think I've done something wrong with my variable typing. I ran this in Ruby and it runs just fine so I know it's not a hardware issue...
Could someone help me find what I did wrong in this? I'm still digging, too. I just started working with Crystal this week. This is my second application/experiment with it. I really like, but I am not yet aware of some of its idiosyncrasies.
EDIT
Updated script to reflect suggested change and outcome of runtime from said change. With said change, I can now run the program successfully over the number 45 now but only up to about low 90s. So that's interesting. I'm gonna run through this and see where I may need to add additional explicit casting. It seems very unintuitive that changing the type at the time of initiation didn't "stick" through the entire runtime, which I tried first and that failed. Something doesn't make sense here to me.
Original Results
$ crystal build fib.cr
$ ./fib 45
1836311903
$ ./fib 46
Arithmetic overflow
$ ./fib.rb 460
985864329041134079854737521712801814394706432953315\
510410398508752777354792040897021902752675861
Latest Results
$ ./fib 92
12200160415121876738
$ ./fib 93
Arithmetic overflow
./fib <integer>
Given Fibonacci; determine which fib value would
exist at <integer> index.
Edit ^2
Now also decided that maybe ARGV[0] is the problem. So I changed the call to f() to:
62 begin
63 i = ARGV[0].to_u64.as(UInt64)
64 puts f i
65 rescue e
66 STDERR.puts e
67 usage
68 end
and added a debug print to show the types of the variables in use:
22 return 0 if p == 0
23
24 puts "p: %s\tfib_now: %s\tfib_last: %s\tfib_hold: %s\ti: %s" % [typeof(p), typeof(fib_now), typeof(fib_last), typeof(fib_hold), typeof(i)]
25 loop do
p: UInt64 fib_now: UInt64 fib_last: UInt64 fib_hold: UInt64 i: UInt64
Arithmetic overflow
./fib <integer>
Given Fibonacci; determine which fib value would
exist at <integer> index.
Edit ^3
Updated with latest code after bug fix solution by Jonne. Turns out the issue is that I'm hitting the limits of the structure even with 128 bit unsigned integers. Ruby handles this gracefully. Seems that in crystal, it's up to me to gracefully handle it.
The default integer type in Crystal is Int32, so if you don't explicitly specify the type of an integer literal, you get that.
In particular the lines
fib_last = 0
fib_now = 1
turn the variables into the effective type Int32. To fix this, make sure you specify the type of these integers, given you don't need negative numbers, UInt64 seems most appropriate here:
fib_last = 0u64
fib_now = 1u64
Also note the the literal syntax I'm using here. Your 0.to_i64's create an In32 and then an Int64 out of that. The compiler will be smart enough to do this conversion at compile time in release builds, but I think it's nicer to just use the literal syntax.
Edit answering to to the updated question
Fibonacci is defined as F0 = 0, F1 = 1, Fn = Fn-2 + Fn-1, so 0, 1, 1, 2, 3, 5.
Your algorithm is off by one. It calculates Fn+1 for a given n > 1, in other words 0, 1, 2, 3, 5, in yet other words it basically skips F2.
Here's one that does it correctly:
def fib(n)
return 0 if n == 0
last = 0u64
current = 1u64
(n - 1).times do
last, current = current, last + current
end
current
end
This correctly gives 7540113804746346429 for F92 and 12200160415121876738 for F93. However it still overflows for F94 because that would be 19740274219868223167 which is bigger than 264 = 18446744073709551616, so it doesn't fit into UInt64. To clarify once more, your version tries to calculate F94 when being asked for F93, hence you get it "too early".
So if you want to support calculating Fn for n > 93 then you need to venture into the experimental Int128/UInt128 support or use BigInt.
I think one more thing should be mentioned to explain the Ruby/Crystal difference, besides the fact that integer literals default to Int32.
In Ruby, a dynamically typed interpreted language, there is no concept of variable type, only value type. All variables can hold values of any type.
This allows it to transparently turn a Fixnum into a Bignum behind the scenes when it would overflow.
Crystal on the contrary is a statically typed compiled language, it looks and feels like Ruby thanks to type inference and type unions, but the variables themselves are typed.
This allows it to catch a large number of errors at compile time and run Ruby-like code at C-like speed.
I think, but don't take my word for it, that Crystal could in theory match Ruby's behavior here, but it would be more trouble than good. It would require all operations on integers to return a type union with BigInt, at which point, why not leave the primitive types alone, and use big integers directly when necessary.
Long story short, if you need to work with very large integer values beyond what an UInt128 can hold, require "big" and declare the relevant variables BigInt.
edit: see also here for extreme cases, apparently BigInts can overflow too (I never knew) but there's an easy remedy.
Consider the set of all bit arrays of length n. Now consider the set of all 1-to-1 functions that map from this set to this set.
Now select a single function out of the latter set. Is there any algorithm to find a "minimal" method of implementing this function? Assume that we only have access to fundamental bit array operators such as AND OR XOR NOT and left and right bitshifts.
In case you're wondering, the reason I want this is because I'm writing an algorithm to convert from z-curve ordering of bits to hilbert-curve ordering of bits. My current method is to make a lookup table, but I bet there's a better option.
As a simple example, let's say I have a truth table that looks like this:
00 -> 10
01 -> 01
10 -> 00
11 -> 11
Then I should be able to infer that, given an input bit string input, the output bit string output is (in java syntax)
output = ((~input) << 1) ^ input
Here's the proof in this case:
00 -> 11 -> 10 -> 10
01 -> 10 -> 00 -> 01
10 -> 01 -> 10 -> 00
11 -> 00 -> 00 -> 11
I'm trying to use the indices of a sorted column of a dataset. I want to reorder the entire dataset by one sorted column.
area.sort<-sort(xsample$area1, index.return=TRUE)[2]
The output is a list, so I can't use it index through the whole dataset.
Error in xj[i] : invalid subscript type 'list'
Someone suggested using unlist but I can't get rid of the ix*.
Any ideas? Thanks
> area.sort<-unlist(area.sort)
ix1 ix2 ix3 ix4 ix5 ix6 ix7 ix8 ix9 ix10 ix11 ix12 ix13
45 96 92 80 53 54 24 21 63 81 40 66 64
The call to sort with index.return=TRUE returns a list with two components: x and ix. Indexing with [2] returns a subset of the list - still a list.
If you index using [[2]] it should work better. That returns the element in the list.
But indexing using $ix is perhaps a bit clearer.
But then again, if you only need the sorted indices, you should call order instead of sort...
I am a newbie to R and I have problem splitting a very large data frame into a nested list. I tried to look for help on the internet, but I was unsuccessful.
I have a simplified example on how my data are organized:
The headers are:
1 "station" (number)
2. "date.str" (date string)
3. "member"
4. "forecast time"
5. "data"
I am not sure my data example will show up rightly, but if so, it look like this:
1. station date.str member forecast.time data1
2. 6019 20110805 mbr000 06 77
3. 6031 20110805 mbr000 06 28
4. 6071 20110805 mbr000 06 45
5. 6019 20110805 mbr001 12 22
6. 6019 20110806 mbr024 18 66
I want to split the large data frame into a nested list after "station", "member", "date.str" and "forecast.time". So that mylist[[c(s,m,d,t)]] contains a data frame with data for station "s" and member "m" for date.str "d" and for forecast time "t" conserving the values of s, m, d and t.
My code is:
data.st <- list()
data.st.member <- list()
data.st.member.dato <- list()
data.st. <- split(mydata, mydata$station)
data.st.member <- lapply(data.st, FUN = fsplit.member)
(I created a function to split after "member")
#Loop over station number:
for (s in 1:S){
#Loop over members:
for (m in 1:length(members){
tmp <- split( data.st.member[[s]][[m]], data.st.member[[s]][[m]]$dato.str )
#Loop over number of different "date.str"s
for (t in 1:length(no.date.str) ){
data.st.member.dato[[s]][[m]][[t]] <- tmp}
} #end m loop
} #end s loop
I would also like to split according to the forecast time: forec.time, but I didn't get that far.
I have tried a couple of different configurations within the loops, so I don't at the moment have a consistent error message. I can't figure out, what I am doing or thinking wrong.
Any help is much appreciated!
Regards
Sisse
It's easier than you think. You can pass a list into split in order to split on several factors.
Reproducible example
with(airquality, split(airquality, list(Month, Day)))
With your data
data.st <- with(mydata,
split(mydata, list("station", "member", "date.str", "forecast.time"))
)
Note: This doesn't give you a nested list like you asked for, but as Joran commented, you very probably don't want that. A flat list will be nicer to work with.
Speculating wildly: did you just want to calculate statistics on different chunks of data? If so, then see the many questions here on split-apply-combine problems.
I also want to echo the others in that this recursive data structure is going to be difficult to work with and probably there are better ways. Do look at the split-apply-combine approach as Richie suggested. However, the constraints may be external, so here is an answer using the plyr library.
mylist <- dlply(mydata, .(station), dlply, .(memeber), dlply, .(date.str), dlply, .(forecast.time), identity)
Using the snippet of data you gave for mydata,
> mylist[[c("6019","mbr000","20110805","6")]]
station date.str member forecast.time data1
1 6019 20110805 mbr000 6 77