Solving the length-of-missing-array Codewars kata

24 views
Skip to first unread message

edA-qa mort-ora-y

unread,
Aug 13, 2017, 10:46:38 AM8/13/17
to Leaflang
It took most of the day but I got Leaf to solve the kata: https://www.codewars.com/kata/57b6f5aadb5b3d0ae3000611

This is the Leaf solution, complete with all the TODO's and ugly code bits. I've got work to do.

import std

defn min = ( x, y ) -> {
	return x < y ? x| y
}

defn max = ( x, y ) -> {
	return x > y ? x  | y
}

defn get_length_of_missing_array = ( arrays : arrayarrayany」」 ) -> {
	arrays.size == 0 then return 0
	
	var mn = arrays#0.size
	var mx = mn
	for x in std.range(0, arrays.size) {
		var a = arrays#x
		a.size == 0 then return 0
		
		mn = min(mn, a.size)
		mx = max(mx, a.size)
	}
	
 	var xlen = arrays.size + 1
 	//TODO: accidental "min" failed to produce a useful error
 	mx != mn + (xlen-1) then return -2
	
	//TODO: "bool" failed to produce useful error
 	var hs = arrayboolean」(xlen)
 	for x in std.range(0, arrays.size) {	
		var sz = arrays#x.size
 		hs#(arrays#x.size - mn) = true
 	}
	
	for x in std.range(0, xlen) {
		//TODO: this was failing to print, even though I added a boolean output
		//std.print( [ x, "=", hs#x, "\n" ] )
		hs#x else return x + mn
	}
	
	return 0
}

//TODO: we don't have tuple -> array conversion yet, but foreach on a tuple should work...
//defn test_it = ( lens : array「integer」 ) -> {
defn test_it = ( expect : integer, lens : tuple ) -> {

	var sz = lens.size
	var q = arrayarrayinteger」」(sz)
	//for x in std.range(0, sz) {
	//	q#x = array「integer」(lens#x)
	//}
	
	//...kind of yucky, maybe foreach should be able to provide an index?
	var x = 0
	foreach( lens, (v:integer)-> {
		q#x = arrayinteger」(v)
		x = x + 1
	})
	
	var l = get_length_of_missing_array(q)
	l != expect then {
		std.print([ expect, " != ", l, "\n"] )
		//TODO: pre-clone failure
		//fail tag_string( "incorrect" )
	}
}

var main = -> {
	test_it( 3, [2,4,1,5] )
	test_it( 2, [3,4,1,5] )
	test_it( 5, [3,2,4,1,6] )
	test_it( 0, [] )
	test_it( 0, [2,0])
}
Reply all
Reply to author
Forward
0 new messages