Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

c)

Code Block
function [questions, solutions] = letterQuestion(capitals)
	nSolutions = 0;
	while nSolutions == 0
		letter = randomLatinLetter(true);
		solutions = beginsWith(capitals, letter);
		nSolutions = length(solutions);
	end
	questions = sprintf('Capital starting with %s ?', letter);
end

d) 

Code Block
function result = nLetters(city)
	result = length(city);
	for i = city
		if city(i) == ' '
			result = result  -1;
		end
	end
end

e)

 

 

 

Code Block
function withLength = hasLength(capitals, length)
    withLength = {};
    for city = capitals
        if nLetters(city{1}) == length
            withLength(end+1) = city;
        end
    end
end

 

f)

 

Code Block
 function [que, sol] = lengthQuestion(capitals)
    okLengths = [];
    for city = capitals 
        len = nLetters(city{1});
        if sum(len == okLengths) == 0
            okLengths(end + 1) = len;
        end
    end 
    randomLength = okLengths(randi(length(okLengths)));    
    que = sprintf("Capital with %i letters? ", randomLength);
    sol = hasLength(capitals, randomLength);
end

 

g)

 

Code Block
function [que, sol] = randomQuestion(capitals)
	qType = randi([0,1]);                          
	if qType == 0                                 
    	[que, sol] = letterQuestion(capitals);      
	else
    	[que, sol] = lengthQuestion(capitals);      
	end
end

 

 

 

h)

Code Block
function playQuiz(capitals):
keepOn = True
points = 0
while keepOn
    [quest, sol] = randomQuestion(capitals)
    city = input(quest, 's')
    if strcmp(city, 'q'):
       keepOn = False
    elseif ismember(city, sol):
        disp('Correct!')
        points = points + 1;
    else
       disp('Sorry, that was wrong!')
	end
end
end

i)

Code Block
function main()
disp('CAPITALS QUIZ')
disp('Answer questions to score points.')
disp('To quit, answer q')
points = playQuiz(allCapitals)
if points == 1
    text = '1 point.\n'
else
    text = sprintf('%i points.\n', points)
end
fprintf('Congrats! You scored %s', text)
end



Oppgave Pythagoras
Code Block
function triplets = pythagoreanTriplets(n)
triplets = [];
a = 2;
while true
   [rows, ~] = size(triplets);
   if rows >= n
      return 
   end
   a = a + 1;
   % Ingen vits å lete over denne
   maxSearch = a^2;
   for b = a : maxSearch
      c = sqrt(a^2 + b^2);
      if mod(c, 1) == 0
         triplets = [triplets; a, b, c]; 
      end
   end
end
end





...