Displaying multiple values in for statement in Swift - swift

Hi I am new to programming. I apologize beforehand if this is a stupid question, but I'm learning about For loops. The below is an example code I understand. I know how to write a basic For loop that iterates through a single variable in each loop, but how do I use a For loop to display multiple values in one loop. Example:
let treeArray = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
for tree in treeArray {
print(tree)
}
I want to be able to print three variables in one loop so the code would print
Pine Oak Yew on one line
Maple Birch Myrtle and on the next
Instead of
Pine
Oak
Yew
Maple
Birch
Myrtle
Thanks!

You could use .enumerated() to pair the index with the element and then print(_:terminator:) using index % 3 to select the appropriate terminator (newline "\n" or space " "):
let treeArray = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
for (index, tree) in treeArray.enumerated() {
print(tree, terminator: index % 3 == 2 ? "\n" : " ")
}
Output:
Pine Oak Yew
Maple Birch Myrtle
The general case: printing n items per line
In general, for printing n items per line:
print(tree, terminator: index % n == n - 1 ? "\n" : " ")
or equivalently:
print(tree, terminator: (index + 1) % n == 0 ? "\n" : " ")
If you want the last item to always be followed by a newline, then add an addition check for that:
print(tree, terminator: index % n == n - 1 || index == treeArray.endIndex - 1 ? "\n" : " ")

Use an array to store trees and
joined(separator: String)
on array to stitch them together.
let treeArray = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
var treeNames = [String]()
for (count, tree) in treeArray.enumerated() {
treeNames.append(tree)
if ((count + 1) % 3) == 0 {
let treeLine = treeNames.joined(separator: " ")
print(treeLine)
treeNames.removeAll()
}
}

Related

I'm having trouble with the code where the budget variable wasn't deducting throughout the loop. It instead do nothing or sometimes add up

enter image description hereI'm making an inventory system code and I'm a bit stuck finding a solution to the substraction problem, when I choose "ADD" and entering the input the formula wasn't getting the accurate outcome. For example, if I input Paper001 then its quantity, the output is fine at first but when input another item, the deduction instead becoming addition or sometimes doesn't do anything.
I tried dividing the values in the dictionary in 3 conditions but it turns out even worse.
while True:
try:
bg = float(input("Enter your budget : "))
print("-----------------------------------------------------------")
print(" Item name Item code Item price(Per set) \n")
print("1.Bond Paper : Paper001 100 PHP\n2.Yellow Paper : Paper002 50 PHP\n3.Intermediate Paper : Paper003 20 PHP\n\n")
s = bg
except ValueError:
print("PRINT NUMBER AS A AMOUNT")
continue
else:
break
a ={"name":[], "quant":[], "price":[]}
# converting dictionary to list for further updation
b = list(a.values())
# variable na value of "name" from dictionary 'a'
na = b[0]
# variable qu value of "quant" from dictionary 'a'
qu = b[1]
# This loop terminates when user select 2.EXIT option when asked
# in try it will ask user for an option as an integer (1 or 2)
# if correct then proceed else continue asking options
while True:
try:
print("-----------------------------------------------------------")
ch = int(input("1.ADD\n2.STORAGE LIST\n3.Customer purchase\n4.EXIT\nEnter your choice : "))
except ValueError:
print("\nERROR: Choose only digits from the given option")
continue
else:
# check the budget is greater than zero and option selected
# by user is 1 i.e. to add an item
if ch == 1 and s>0:
p_list={'Paper001':100,'Paper002':50,'Paper003':20}
pn = input("Enter item code : ")
if pn in p_list.keys():
q = int(input("Enter quantity : "))
else:
print("-----------------------------------------------------------")
print("Code is invalid")
continue
#checks if item name is already in the list
if pn in na:
ind = na.index(pn)
# remove quantity from "quant" index of the product
qu.remove(qu[ind])
# new value will be added to the previous value of user's quantity
qu.insert(ind, q)
tpr = (q+q)*p_list[pn]
print(f" Total product price:",tpr)
s = bg-tpr
print("\namount left", s)
else:
# append value of in "name", "quantity", "price"
na.append(pn)
# as na = b[0] it will append all the value in the
# list eg: "name"🙁"rice"]
qu.append(q)
# after appending new value the sum in price
# as to be calculated
tpr = q*p_list[pn]
print("\nTotal product price:",tpr)
s = bg-tpr
if s==0:
print("No more budget left")
print("\nAmount left :", s)
elif s>0:
print("\nAmount left :", s)
else:
print("Insufficient budget. Cannot buy item.")
print("Please restart and re-enter your budget.")
break
elif ch ==2 :
print("\n\n\nStorage list")
print("Item name Stocks ")
for i in range(len(na)):
print(f"{na[i]} {qu[i]}")
continue
elif ch == 3:
print("-----------------------------------------------------------")
p_list={'Paper001':100,'Paper002':50,'Paper003':20}
print("\n\n\nStorage list")
print("Item name Stocks ")
for i in range(len(na)):
print(f"{na[i]} {qu[i]}")
co = input("\nEnter customer's order : ")
if co in p_list.keys():
q = int(input("Enter quantity : "))
sl = qu[i]-q
print("Item is sold!")
print("Stocks left :",sl)
if sl <=0:
print("Please add new items!")
else:
print("-----------------------------------------------------------")
print("Code is invalid")
continue
elif ch==4:
print("")
print("\nThank your for shopping with us!")
break
elif s==0:
print("NO BUDGET LEFT. UNABLE TO ADD ITEMS.")
else:
print("ERROR: Choose only the digits given from the option.")

How to truncate a comma-separated value string with remainder count

I'm trying to achieve string truncate with "& more..." when string is truncated. I have this in picture:
Exact code minus text, in image:
func formatString() -> String {
let combinedLength = 30
// This array will never be empty
let strings = ["Update my profile", "Delete me", "Approve these letters"]
// In most cases, during a loop (no order of strings)
//let strings = ["Update", "Delete", "Another long word"]
let rangeNum = strings.count > 1 ? 2 : 1
let firstN = strings[0..<rangeNum]
// A sum of first 2 or 1
let actualLength = firstN.compactMap { $0.count }.reduce(0, +)
switch actualLength {
case let x where x <= combinedLength:
// It's safe to display all
return strings.map{String($0)}.joined(separator: ", ")
default:
if rangeNum == 2 {
if actualLength <= combinedLength {
return strings.first! + ", " + strings[1] + ", & \(strings.count - 2) more..."
}
return strings.first! + ", & \(strings.count - 1) more..."
}
// There has to be at least one item in the array.
return strings.first!
}
}
While truncateMode looks like a match, it's missing the , & n more... where n is the remainder.
My code may not be perfect but was wondering how to refactor. I feel there's a bug in there somewhere. I've not taken into consideration for larger screens: iPad where I would want to display more comma-separated values, I only look for the max 2 then display "& n more" depending on the size of the array.
Is there a hidden modifier for this? I'm using XCode 13.4.1, targeting both iPhone and iPad.
Edit:
The title is incorrect. I want to convert an array of strings into a comma-separated value string that's truncated using the function I have.

IndexError: string index out of range for Conway's game of life tutorial

I am following a tutorial (from https://automatetheboringstuff.com/2e/chapter4/) for a text-based version of Conway's game of life, and i have put it exactly like the tutorial says and it still produces an IndexError:
the error message is as follows:
print(currentCells[x][y], end='')
IndexError: string index out of range
my goal is to place a blank space while the cells are 'alive' (meeting certain requirements) and a # when they are 'dead' (meeting other requirements)
im confused why the tutorial even when i copy directly from it, gets it wrong. the tutorial is for python 3.8
the entire block of code is as follows:
while True:
print('\n\n\n\n\n')
currentCells = copy.deepcopy(nextCells)
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells[x][y], end='')
print()
for x in range(WIDTH):
for y in range(HEIGHT):
leftCoord = (x - 1) % WIDTH
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
numNeighbors = 0
if currentCells[leftCoord][aboveCoord] == '#':
numNeighbors += 1
if currentCells[x][aboveCoord] == '#':
numNeighbors += 1
if currentCells[rightCoord][aboveCoord] == '#':
numNeighbors += 1
if currentCells[leftCoord][y] == '#':
numNeighbors += 1
if currentCells[rightCoord][y] == '#':
numNeighbors += 1
if currentCells[leftCoord][belowCoord] == '#':
numNeighbors += 1
if currentCells[x][aboveCoord] == '#':
numNeighbors += 1
if currentCells[rightCoord][belowCoord] == '#':
numNeighbors += 1
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and numNeighbors == 3:
nextCells[x][y] = '#'
else:
nextCells[x][y] = ' '
time.sleep(1)
i'm new to coding so i tried commenting out the lines but of course that just renders the other parts that use those functions unusable. also the other questions on this topic seem to be about much more advanced versions of this game. like i said this is one of my first programs.
I'm too new to programming in Python! It's great language to learn:-)
Anyway I think I found the problem with the code. There is small mistake...
If you look at line 25, it says 'nextCells is a list of column list'.
So instead of appending empty string is should be:
line 25: nextCells.append(column)

Swift split substring based on word wrap

junior developer here. I am currently trying to achieve a substring that is split every n characters of a String.
This is my code for the function
public func split(every: Int) -> [String] {
var result = [String]()
for i in stride(from: 0, to: self.count, by: every) {
let startIndex = self.index(self.startIndex, offsetBy: i)
let endIndex = self.index(startIndex, offsetBy: every, limitedBy: self.endIndex) ?? self.endIndex
result.append(String(self[startIndex..<endIndex]))
}
return result
}
The above code works as expected. But there is one lacking from the code above, which is the word wrapping. Here is the sample String
let itemName = "Japanese Matcha SM w RB -L Special Edition And Americano MS w Brown Sugar Limited Edition"
print(itemName.split(every: 26))
The result will be
["Japanese Matcha SM w RB -L", " Special Edition And Ameri", "cano MS w Brown Sugar Limi", "ted Edition"]
Notice the
[" Special Edition And Ameri"], ["cano MS w Brown Sugar Limi"]
I am trying to figure out how to do the word wrap algorithm based on every n character, but couldn't find any clue.
For example, from above case, how to generate the array becomes,
[" Special Edition And"], ["Americano MS w Brown"], ["Sugar"]
So as you can see, the algorithm might check whether every n characters has a word that is being cut out (dynamic check based on the n characters), hence will move the cut word into the next array.
So in that case, the algorithm will cleverly bypass the every n character, might be less, but not more than n characters, if there is any word not being wrapped.
Is my explanation clear? Can anyone guide me please? Thanks
This is some simple implementation of this algorithm, you can start with that.
First we cut string by words, then add them to temporary string until we meet characters limit.
let itemName = "Japanese Matcha SM w RB -L Special Edition And Americano MS w Brown Sugar Limited Edition"
let table = itemName.split(separator: " ")
let limit = 26
var tempString = ""
var finalResult: [String] = []
for item in table {
tempString += item + " "
if tempString.count >= limit {
finalResult.append(tempString)
tempString = ""
}
}
print(finalResult)
How about this?
extension String {
func split(every: Int) -> [String] {
var result = [String]()
let words = self.split(separator: " ")
var line = String(words.first!)
words.dropFirst().forEach { word in
let word = " " + String(word)
if line.count + word.count <= every {
line.append(word)
} else {
result.append(line)
line = word
}
}
result.append(line)
return result
}
}

Difficulty getting readLine() to work as desired on HackerRank

I'm attempting to submit the HackerRank Day 6 Challenge for 30 Days of Code.
I'm able to complete the task without issue in an Xcode Playground, however HackerRank's site says there is no output from my method. I encountered an issue yesterday due to browser flakiness, but cleaning caches, switching from Safari to Chrome, etc. don't seem to resolve the issue I'm encountering here. I think my problem lies in inputString.
Task
Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail).
Input Format
The first line contains an integer, (the number of test cases).
Each line of the subsequent lines contain a String, .
Constraints
1 <= T <= 10
2 <= length of S < 10,000
Output Format
For each String (where 0 <= j <= T-1), print S's even-indexed characters, followed by a space, followed by S's odd-indexed characters.
This is the code I'm submitting:
import Foundation
let inputString = readLine()!
func tweakString(string: String) {
// split string into an array of lines based on char set
var lineArray = string.components(separatedBy: .newlines)
// extract the number of test cases
let testCases = Int(lineArray[0])
// remove the first line containing the number of unit tests
lineArray.remove(at: 0)
/*
Satisfy constraints specified in the task
*/
guard lineArray.count >= 1 && lineArray.count <= 10 && testCases == lineArray.count else { return }
for line in lineArray {
switch line.characters.count {
// to match constraint specified in the task
case 2...10000:
let characterArray = Array(line.characters)
let evenCharacters = characterArray.enumerated().filter({$0.0 % 2 == 0}).map({$0.1})
let oddCharacters = characterArray.enumerated().filter({$0.0 % 2 == 1}).map({$0.1})
print(String(evenCharacters) + " " + String(oddCharacters))
default:
break
}
}
}
tweakString(string: inputString)
I think my issue lies the inputString. I'm taking it "as-is" and formatting it within my method. I've found solutions for Day 6, but I can't seem to find any current ones in Swift.
Thank you for reading. I welcome thoughts on how to get this thing to pass.
readLine() reads a single line from standard input, which
means that your inputString contains only the first line from
the input data. You have to call readLine() in a loop to get
the remaining input data.
So your program could look like this:
func tweakString(string: String) -> String {
// For a single input string, compute the output string according to the challenge rules ...
return result
}
let N = Int(readLine()!)! // Number of test cases
// For each test case:
for _ in 1...N {
let input = readLine()!
let output = tweakString(string: input)
print(output)
}
(The forced unwraps are acceptable here because the format of
the input data is documented in the challenge description.)
Hi Adrian you should call readLine()! every row . Here an example answer for that challenge;
import Foundation
func letsReview(str:String){
var evenCharacters = ""
var oddCharacters = ""
var index = 0
for char in str.characters{
if index % 2 == 0 {
evenCharacters += String(char)
}
else{
oddCharacters += String(char)
}
index += 1
}
print (evenCharacters + " " + oddCharacters)
}
let rowCount = Int(readLine()!)!
for _ in 0..<rowCount {
letsReview(str:String(readLine()!)!)
}