[lua] Check if Sudoku puzzle row, column, box is valid

function checkRow(row, numb)
	local hit = {}
	for coll = 1, 9, 1 do
		if not inTable(hit, numb[row][coll]) then		
			if not (numb[row][coll] == 0) then
				table.insert(hit, numb[row][coll])
			end
		else
			return false
		end
	end
return true
end

function checkColl(coll, numb)
	local hit = {}
	for row = 1, 9, 1 do
		if not inTable(hit, numb[row][coll]) then	
			if not (numb[row][coll] == 0) then
				table.insert(hit, numb[row][coll])
			end
		else
			return false
		end
	end
return true
end

function checkBox(row, coll, numb)
	local hit = {}
	for i = row, row+2, 1 do
		for j = coll, coll+2, 1 do
		
			if not inTable(hit, numb[i][j]) then	
				if not (numb[i][j] == 0) then
					table.insert(hit, numb[i][j])
				end
			else
				return false
			end
		end
	end
	return true
end

function isValid()
	for i = 1, 9, 1 do
		if not checkRow(i, numberTable) then
			return false
		end
	end
	
	for i = 1, 9, 1 do
		if not checkColl(i, numberTable) then
			return false
		end
	end
	
	for i = 1, 9, 3 do
		for j = 1, 9, 3 do
			if not checkBox(i, j, numberTable) then
				return false
			end
		end
				
	end
	return true
	
end

function inTable(tbl, item)
    for key, value in pairs(tbl) do
        if value == item then return true end
    end
    return false
end

numberTable is two dimensional table.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s