Lektion 4: lösningsförslag

  1. // 1
  2. class Person
  3. {
  4. public string FirstName;
  5. public string LastName;
  6. public int Age;
  7. }
  8. ...
  9. Person p = ...;
  10. string summary = p.FirstName + " " + p.LastName + " är " + p.Age + " år gammal.";
  11. // 2
  12. class Company
  13. {
  14. public string Name;
  15. public string Headquarters;
  16. public int Age;
  17. }
  18. Company c1 = ...;
  19. Company c2 = ...;
  20. Company merger = new Company
  21. {
  22. Name = c1.Name + "-" + c2.Name,
  23. Headquarters = c1.Headquarters,
  24. Age = 0
  25. };
  26. // 3
  27. string s = ...;
  28. int count = 0;
  29. foreach (char c in s)
  30. {
  31. if (c == 'X')
  32. {
  33. count += 1;
  34. }
  35. }
  36. // 3.1
  37. // Varje tecken kan typkonverteras till ett unikt heltal och sedan jämföras med de två numeriska intervall som engelska bokstäver råkar ligga inom.
  38. // 4
  39. int[] numbers = ...;
  40. int largest = numbers[0];
  41. foreach (int i in numbers)
  42. {
  43. if (i > largest)
  44. {
  45. largest = i;
  46. }
  47. }
  48. // 4.1
  49. // Ungefär samma som ovan fast när den äldsta personen hittas ska resultatvariabeln tilldelas personobjektet, inte åldern.
  50. // 4.2
  51. // Ungefär samma som ovan, fast varje gång den äldsta personen hittas måste förnamnet också sparas och sedan före nästa tilldelning jämföras med nästa persons förnamn om åldern råkar vara samma.
  52. // 5
  53. string[] words = ...;
  54. string target = "apple";
  55. int position = -1;
  56. for (int i = 0; i < words.Length; i += 1)
  57. {
  58. string w = words[i];
  59. if (w == target)
  60. {
  61. position = i;
  62. }
  63. }
  64. // 5.1
  65. // Studera valfri implementation av binärsökning ("binary search").
  66. // 6
  67. string text = ...;
  68. int periods = 0;
  69. int spaces = 0;
  70. foreach (char c in text)
  71. {
  72. if (c == '.')
  73. {
  74. periods += 1;
  75. }
  76. else if (c == ' ')
  77. {
  78. spaces += 1;
  79. }
  80. }
  81. int wordCount = spaces + 1;
  82. int sentenceCount = periods;
  83. double averageWordCount = (double) wordCount / sentenceCount;
  84. // 7
  85. string[] strings = ...;
  86. int highest = 0;
  87. string result = null;
  88. foreach (string s1 in strings)
  89. {
  90. int occurrences = 0;
  91. foreach (string s2 in strings)
  92. {
  93. if (s1 == s2)
  94. {
  95. occurrences += 1;
  96. }
  97. }
  98. if (occurrences > highest)
  99. {
  100. highest = occurrences;
  101. result = s1;
  102. }
  103. }